#!/usr/bin/perl
# Written by Charlton Harrison
# Takes piped input and processes it

$increment_place = 30;	# Number of binary decimal places per unit of work

open(IN, "/tmp/distpalin.tmp");

$linecount = 0;
while (<IN>) {
    chop;
    $data[$linecount] = $_;
    $linecount++;
}

`rm -f /tmp/distpalin.tmp`;
$linecount = $linecount - 1;


# First line is the starting half
# Then are the results
# Then the auth code

$addflag = 0;
open(LIN, "list");
open(LOUT, ">list.new");
while (<LIN>) {
    $line = $_;
    $line =~ m/^([0,1]+)/;
    $lasthalf = $1;
    if (($lasthalf == $data[0]) && ($line =~ m/$data[$linecount]/)) {
	# If any results write them to the results file
	if ($linecount > 1) {
	    open(RESULTS, ">>results");
	    for ($i=1; $i<$linecount; $i++) {
		print RESULTS $data[$i], "\n";
	    }
	    close(RESULTS);
	}
	chop($line);
	print LOUT $line . " done\n";
	$addflag = 1;
    } else {
	print LOUT $line;
    }
}
# If a work unit has been completed,  add another entry to the end of the list
if ($addflag) {   # Add another entry to the end of the list
    # Increment $lasthalf
    $lhn = 0;
    while ($lasthalf ne "") {
	$lh[$lhn] = chop($lasthalf);
	$lhn++;
    }
    $i = $increment_place;
    $lh[$i]++;
    while ($lh[$i] > 1) {
	$lh[$i] = 0;
	$i++;  $lh[$i]++;
    }
    # Print the new binary half
    if ($i > $lhn) { $lhn = $i; }
    for ($i=$lhn; $i>=0; $i--) {
	print LOUT $lh[$i];
    }
    print LOUT " ";
    # Generate a random 8-digit hex number
    for ($i=0; $i<8; $i++) {
	$rnd = int(rand 16);
	if ($rnd == 10) { $rnd = "a"; }
	if ($rnd == 11) { $rnd = "b"; }
	if ($rnd == 12) { $rnd = "c"; }
	if ($rnd == 13) { $rnd = "d"; }
	if ($rnd == 14) { $rnd = "e"; }
	if ($rnd == 15) { $rnd = "f"; }
	print LOUT $rnd;
    }
    print LOUT "\n";
}
close(LIN);
close(LOUT);
`cp -f list.new list`;
`rm -f list.new`;

