#!/usr/bin/perl

open FHAND, "<code-pf.txt";
@lines = <FHAND>;
close FHAND;

chomp @lines;

foreach (@lines) {
  tr/a-z/A-Z/;
  tr/J/I/;
  s/[^A-Z]//g;
}

@chars = split('',$lines[0]);

@grid = ();
foreach (@chars) {
  $tally{$_}++;
  if ($tally{$_} == 1) {
    push @grid, $_;
  }
}
foreach ('A'..'Z') {
  next if ($_ eq 'J');
  $tally{$_}++;
  if ($tally{$_} == 1) {
    push @grid, $_;
  }
}

foreach $row (0..4) {
  foreach $col (0..4) {
    print $grid[$row*5+$col];
  }
  print "\n";
}

foreach (0..24) {
  $rrev{$grid[$_]} = int($_ / 5);
  $crev{$grid[$_]} = $_ % 5;
}

$pos = 0;  
@code = split('',$lines[1]);
while ($pos < scalar @code) {
  $r1 = $rrev{$code[$pos]};
  $r2 = $rrev{$code[$pos+1]};
  $c1 = $crev{$code[$pos]};
  $c2 = $crev{$code[$pos+1]};
#  print "\n$r1$c1$r2$c2$code[$pos]$code[$pos+1] -> ";
  if ($r1 == $r2) { $r1--; $r2--; }
  if ($c1 == $c2) { $c1--; $c2--; ($r1,$r2) = ($r2, $r1);}
  if ($r1 == $r2 and $c1 == $c2) { $c1++; $c2++; }
  $r1 = 4 if ($r1 == -1);
  $c1 = 4 if ($c1 == -1);
  $r2 = 4 if ($r2 == -1);
  $c2 = 4 if ($c2 == -1);
  print $grid[$r1*5+$c2],$grid[$r2*5+$c1];
  $pos += 2;
}
print "\n";

