#!/usr/bin/perl
#
# This code is public domain code.

$seq = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789+-';
$q = "";
sub decode
{
    ($encoded) = @_;
    @s = map { index($seq,$_); } split(//,$encoded);
    $l = ($#s+1) % 4;
    if ($l)
    {
	if ($l == 1)
	{
	    print "Error!";
	    return;
	}
	$l = 4-$l;
	$#s += $l;
    }
    $r = '';
    while ($#s >= 0)
    {
	$n = (($s[0] << 6 | $s[1]) << 6 | $s[2]) << 6 | $s[3];
	$r .=chr(($n >> 16) ^ 67) .
	     chr(($n >> 8 & 255) ^ 67) .
	     chr(($n & 255) ^ 67);
	@s = @s[4..$#s];
    }
    $r = substr($r,0,length($r)-$l);
    return $r;
}

sub validate
{
#Validate the UAC by refusing strings with non-numbers.
#Current plan. Take in string. Copy string. Chop string repeatedly, 
#If a string member is non-number, return false. If not, return true.

    my $dude = 0;                            #Initialize $dude 
    $stringy = $results[2];                   #make private copy of string

    for ($i = (length $stringy);$i !=0;$i--){ #Go through the string
	$dude = chop $stringy;                #Cut off the end

#	print "$dude\n";
	unless ($dude =~ (/\d/)  )                   #Unless it's a number
	{
	    print "Not Valid!\n"; #Print error and return 0 (false)
	    return 0;           

	}
    }
    return 1;

}
open(MYOUTFILE, ">isbns.txt");
while ($s != -1) {
    $s = <STDIN>;
    chomp($s);
    @fields = split(/\./,$s);
    @results = map(decode($_), @fields[1..$#fields]);
    if ($#results == 2)
    {
	if (length "$results[2]" > 12)
	{
	    if (validate == 1)
	    {
		print "$results[2]\n";
		print MYOUTFILE "$results[2]\n";
	    }
	    else
	    {
		print "$results[2] Failed Validation!\n";
	    }
	}
	else
	{
	    print "$results[2] Short\n"
	}
    }
    else
    {
	print join("\n",@results);
    }
    
}
close(MYOUTFILE);


    
