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

use strict;

my $key;
my $haywyre_doc;
my $enc;
my $decoded_html;

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

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

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

$enc = special($enc);

$decoded_html = decode($key, $enc);
print STDOUT "decoded HTML:\n$decoded_html\n\n";

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;
}

