#!/usr/bin/perl -w
use strict;

my $doDecode= 0;
GetOptions(
	"d" => \$doDecode,
);

if ($doDecode) {
	my ($input_filename, $corrected_filename)= @_;
	my $inputtext= ReadFile($input_filename);
	my $correctedtext= ReadFile($corrected_filename);

	my $decodedtext= demangle($inputtext, $correctedtext);

	print $decodedtext;

}
else {
	my ($plain_filename, $transport_filename)= @_;
	my $plaintext= ReadFile($plain_filename);
	my $transporttext= ReadFile($transport_filename);

	my $encodedtext= demangle($plaintext, $transporttext);

	print $encodedtext;
}
exit(0);

sub mangle {
	my ($transporttext, $sourcetext)= @_;

	my $result= "";

	my $source= ConverToNumber($sourcetext);

	for (split(/([a-z]{4,})/i, $transporttext)) {
		if (/([a-z]{4,})/i) {
			my $word= $_;
			my $nrofperms= faculty(length($word)-2)
			$code= $source % $nrofperms;
		   $source = ($source-$code)/$nrofperms;
			$result .= mangleword($word, $code);
		}
		else {
			$result .= $_;
		}
	}

	return $result;
}
sub demangle {
	my ($receivedtext, $correctedtext)= @_;


	my @received= split(/([a-z]{4,})/i, $receivedtext);
	my @corrected= split(/([a-z]{4,})/i, $correctedtext);
	die "texts don't match\n" if ($#received != $#corrected);

	my $original= 0;

	for (my $i=0 ; $i<=$#received ; $i++) {
		my $rcv= $received[$i];
		my $cor= $corrected[$i];
		if ($rcv =~ /([a-z]{4,})/i) {
			die "texts don't match\n" if ($cor !~ /([a-z]{4,})/i);
			die "texts don't match\n" if (length($cor)!=length($rcv));

			my $nrofperms= faculty(length($rcv)-2)
			$code= getwordmangle($rcv, $cor);
			$original = $original*$nrofperms + $code;
		}
		else {
			die "texts don't match\n" if ($cor =~ /([a-z]{4,})/i);
		}
	}

	my $originaltext= NumberToText($original);

	return $result;
}

