#!/usr/bin/perl -w

use strict;
use v5.30;

my @code = map { chomp; [ split /\s+/ ] } <>;

my $ip = 0;

my %tgl = (
	cpy => 'jnz',
	inc => 'dec',
	dec => 'inc',
	jnz => 'cpy',
	tgl => 'inc',
);

my %regs = (a => 12);
# my %regs = (a => 479001600, b => 1, c => 2, d => 0);
# $code[24][0] = 'dec'; # after b=4
# $code[22][0] = 'dec'; # after b=3
# $code[20][0] = 'cpy'; # after b=2
# $code[18][0] = 'cpy'; # after b=2
# $code[16][0] = 'inc'; # after b=1
my $debug = 0;
# $ip = 17;
while ($ip < @code) {
	say join(' ', $ip, @{ $code[$ip] }, map { "$_=$regs{$_}" } sort keys %regs)
		if $debug;
	$debug = 0;
	my @ins = @{ $code[$ip] };
	if ($ins[0] eq 'cpy') {
		my $val = $ins[1];
		my $reg = $ins[2];
		$val = $regs{$val} if $val =~ /[a-z]/;
		$regs{$reg} = $val;
	} elsif ($ins[0] eq 'inc') {
		$regs{$ins[1]}++;
	} elsif ($ins[0] eq 'dec') {
		$regs{$ins[1]}--;
	} elsif ($ins[0] eq 'jnz') {
		my ($reg, $val) = @ins[1..2];
		if ($val eq '-2' && $ip >= 2 && $code[$ip-1][0] eq 'dec'
			&& $code[$ip-2][0] eq 'inc'
			&& $code[$ip-1][1] eq $reg) {
			$regs{$code[$ip-2][1]} += $regs{$reg};
			$regs{$reg} = 0;
		}
		$val = $regs{$val} if $val =~ /[a-z]/;
		$reg = $regs{$reg} if $reg =~ /[a-z]/;
		if ($reg) {
			$ip += $val - 1;
		}
	} elsif ($ins[0] eq 'tgl') {
		my $off = $ins[1];
		$off = $regs{$off} if $off =~ /[a-z]/;
		my $other = $code[$ip + $off];
		say "toggle ", $ip+$off, " $other->[0] to $tgl{$other->[0]}"
			if $other;
		$debug = 1;
		$other->[0] = $tgl{$other->[0]} if $other;
	} else {
		say "Unknown instrution: $_";
	}
	$ip++;
}

say $ip;
say $regs{a};

