#!/usr/bin/perl
use strict;

main();

sub main {
  my %words;

  while (<>) {
    chomp;
    s/\r$//;
    $words{lc($_)} = $_;
  }

  print "analyzing " . keys(%words) . " words\n";
  foreach my $word (sort keys %words) {
    my $r13 = rot13($words{$word});
    if ($words{lc($r13)}) {
      print "W: $words{$word} | $r13\n";
    }
    if (is_anagram($word, $r13)) {
      print "A: $words{$word} | $r13\n";
    }
  }
}

sub rot13 {
  local $_ = shift @_;
  tr/a-zA-Z/n-za-mN-ZA-M/;
  return $_;
}

sub is_anagram {
  my ($one, $two) = @_;
  return 0 if (length($one) != length($two));
  my @ltrs_one = sort(split(//, $one));
  my @ltrs_two = sort(split(//, $two));
  foreach my $i (0 .. $#ltrs_one) {
    return 0 if ($ltrs_one[$i] ne $ltrs_two[$i]);
  }
  return 1;
}

__END__

=head1 NAME

B<rot13analyzer> - Searches word lists for interesting rot-13 results

=head1 SYNOPSIS

B<rot13analyzer> wordlist.txt [ wordlist2.txt ... ]

=head1 DESCRIPTION

Reads one or more word list files, specified on command line, and
finds rot-13 word pairs and rot-13 anagrams.  Word lists must be
formatted with one word per line.

Each line of the output is prefixed with either a "W" for word pair,
or a "A" for anagram.

=head1 DEFINITIONS

rot-13 word pair: One word of a rot-13 word pair will produce the
other when you run rot-13 on it. For example: abjurer -> nowhere

rot-13 anagram: A rot-13 anagram occurs when rot-13 produces the
same letters, but rearranged.  For example, bought -> obhtug.

=head1 AUTHOR

Darin Franklin <dfranklin@pobox.com>

=cut
