#!/usr/bin/perl

$crib = "s to pr ed pe ng ui nf re nz ys to p" ;

$ct = readlntostring() ;
@tt = parseintopairs($ct) ;
print "input text:\n" ;
printdi(0,-1,8,@tt) ;
@crib = parseintopairs("X".$crib."X") ;
print "\ncrib text:\n" ;
printdi(0,-1,100,@crib) ;

#pairbyoffset(10,@tt) ;
print "\ncrib found:\n" ;
@ttcrib = @tt[39...51] ;
printdi(0,-1,100, @ttcrib) ;
printdi(0,-1,100,@crib) ;

for ( $i=0; $i<@ttcrib; $i++ ) {
   $cipherdict{$ttcrib[$i]} = $crib[$i] ;
   $cipherdict{reverse($ttcrib[$i])} = reverse($crib[$i]) ;
}
$cipherdict{"UF"}="en" ;
$cipherdict{"BG"}="dx" ;

print "\nPartially decoded:\n" ;
printcipherplain( \%cipherdict, \@tt ) ;

print "\ncodons sorted:\n" ;

@stt = sort(@tt) ;
printdi(0,-1,8,@stt) ;

sub printcipherplain {
  local( %cd, @ct, $i, $l1, $l2, $a ) ;
  %cd = %{$_[0]} ;
  @ct = @{$_[1]} ;
  $l1 = "" ;
  $l2 = "" ;
  for ( $i=0; $i<@ct; $i++ ) {
    $l1 .= $ct[$i]." " ;
    if ( $cd{$ct[$i]} ) {
      $l2 .= $cd{$ct[$i]}." " ;
    }
    else { $l2 .= "   " ; }
    if ( $i%8==7 ) {
      print $l1,"\n" ;
      print $l2,"\n" ;
      $l1 = "" ;
      $l2 = "" ;
    }
  }
}

sub readlntostring {
  local( $s,$l ) ;
  while ( $l=<> ) { chop $l ; $s .= $l ; }
  return $s ;
}


sub printdi {
  local( $sp, $ep, $sk, @di ) = @_ ;
  local( $nlending ) ;
  if ( $ep<0 ) { $ep=@di ; }
  for ( $i=$sp; $i<$ep; $i++ ) {
    print $di[$i]   ;
    $nlending=0 ;
    if ( $i%$sk==($sk-1) ) { 
        print "\n" ; 
        $nlending = 1 ;
    } 
    else { print " " ; }
  }
  if ( $nlending==0 ) { print "\n" ; }
}

sub parseintopairs {
   local ( $line, $t, @text ) , ;
   $line = $_[0] ;
   $i = 0 ;
   while ( $line=~/(\w)\s*(\w)(.*)/ ) {
      $line = $3 ;
      $s = $1.$2 ;
      if ( $s=~/XX/ ) { next ; } 
      $text[$i++] .= $s ;
   }
   return @text ;
}

sub pairbyoffset {
   local ( $offset, @text) = @_ ;
   for ( $i=0 ; $i<@text-$offset; $i++ ) {
      if ( ($text[$i] cmp $text[$i+$offset])==0 ) {
print $i, $text[$i], "\n" ;
      }
      $text[$i]=~/(\w)(\w)/ ;
      if ( ($test[$i+$offset] cmp $2.$1)== 0 ) {
print $i, $2.$1, " (reverse)\n" ;
      }
   }
   print "\n" ;
}

