#!/usr/local/bin/perl -w

use strict;

my $verbose=1;
my $debug=0;
my($haywyre_doc,$key,$enc);

while(<>) {
  $haywyre_doc .= $_;
}

# get the key
($key = $haywyre_doc) =~ s|.*var alf\s*=\s*"(.*)";.*|$1|s;
# now take care of specials
$key = special($key);

# and the encoded document
($enc = $haywyre_doc) =~ s|.*d\("(.*)"\);.*|$1|s;
$enc=special($enc);

my $decoded_html = decode($key, $enc);
print STDERR "decoded HTML:\n$decoded_html\n";
exit 0;

sub decode {
  my($k, $e) = @_;
  my($position);
  my($midpoint) = length($k) / 2;
  my($decoded) = "";
  my($difference, $c);
  my $x;

  for($x = 0; $x < length($e); $x++) {
    my($i,$char);
    $c = substr($e, $x, 1);
    $position = index($k, $c);
    if($position > $midpoint) {
      $difference = $position - $midpoint;
      $i = int(48 - $difference);
      $char = substr($k, $i, 1);
      $decoded .= $char;
    } else {
      $difference = $midpoint - $position;
      $i = int(48 + $difference);
      $char = substr($k, $i, 1);
      $decoded .= $char;
    }
  }
  return $decoded;
}

sub special {
  my($s)=@_;

  $s =~ s/\\"/"/g;
  $s =~ s/\\ / /g;
  $s =~ s/\\\|/|/g;
  $s =~ s/\\'/'/g;
  $s =~ s|\\/|/|g;
  $s =~ s/\\t/\t/g;
  $s =~ s/\\`/`/g;
  $s =~ s/\\n/\n/g;
  $s =~ s/\\\[/[/g;
  $s =~ s/\\\]/]/g;
  $s =~ s/\\\\/\\/g;
  $s;
}
