#!/usr/athena/bin/perl
#
#  This is an anagram decoder for the 1996 IAP Mystery Hunt puzzle 13b.
#  It takes a keyword, translates the letters of the key to their
#  alphabetical value, and uses that as an alphabetical offset from 
#  one letter of the scrambled text to the next one of cleartext.
#  (The key pattern repeats until all characters are accounted for.)

use Getopt::Std; &getopt('kKtT');

if( $opt_h ) {
    print "Usage: augustus -k <key> [crypt text file]\n";
    exit( 0 );
}

%value 
    = (
       'a', 1, 'b', 2, 'c', 3, 'd', 4, 'e', 5, 'f', 6, 'g', 7,
       'h', 8, 'i', 9, 'j', 10, 'k', 11, 'l', 12, 'm', 13, 'n', 14,
       'o', 15, 'p', 16, 'q', 17, 'r', 18, 's', 19, 't', 20, 'u', 21,
       'v', 22, 'w', 23, 'x', 24, 'y', 25, 'z', 26 );

if( $opt_k ) {
    $opt_k =~ s/[^a-zA-Z]//g;	# strip non-alphabetics
    $opt_k =~ tr/A-Z/a-z/;	# downcase
    @alpha_key = split( //, $opt_k );
    for( @alpha_key ) { push( @key, $value{$_} ); }
}

$/ = "\n\n";
@inputs = <>;		# stdin or filename on command line
$/ = "\n";
for( @inputs ) { 
    s/^[\s\-]*//;
    s/[\s\-]*$//;
    s/\n//g;
    next if length( $_ ) < 2;
    @crypt_text = split( //, $_ );
    @clear_text = ();
    for( $i=0, $j=0; $i<=$#crypt_text && $#crypt_text>=0 ; $j++ ) {
	push( @clear_text, splice(@crypt_text, $i, 1) );
	last if $#crypt_text < 0;
	$i = ( $i + $key[$j] ) % ( $#crypt_text + 1 );
#	while( $i > $#crypt_text ) {
#	    $i = $i - $#crypt_text if $i > $#crypt_text;
#	}
	if( $#clear_text == 55 ) {
	    print @clear_text, "\n";
	    @clear_text = ();
	}
    }
    print @clear_text, "\n\n";
}

exit(0);
