#!/pkg/bin/perl -w

$infile = "$ARGV[0]";
open IN, $infile;
close(IN);

$infile =~ m/data(.*)\.txt/;
$i = 1;

$goutprefix = "$ARGV[1]";
chomp ($goutprefix);

$goutfile = $goutprefix . '.' . $i;
open (OUTG, ">$goutfile");

$hsoutprefix = "hapsav";
$hsoutfile = $hsoutprefix . '.' . $i;
open (OUTHS, ">$hsoutfile");

open (OUTTI, '>title');

$eo = 0;
$eo2 = 0;
$numlines = 0;
$numtwos = 0;
$totaltwos = 0;
$nhom = $nhet = 0;

$infile = "$ARGV[0]";
open IN, $infile;

while(<IN>) {
	$line = $_;
	chomp $line;
	
	if ($line =~ /^[01]+$/) {
 		$numlines++;
		$linelength = length($line);

 		if ($eo == 1) {
 			$eo2 = 0;
    			$numtwos = 0;
     			$genoline = "";
     			
     			if($lastline =~ m/[01] [01]/) {
     				@arr1 =  split(/ /, $lastline);
     			} else {
     				@arr1 =  split(//, $lastline);
     				
     			}
     			
     			if($line =~ m/[01] [01]/) {
     				@arr2 =  split(/ /, $line);	
     			} else {
     				@arr2 =  split(//, $line);
     			}
     			
     			for ($j = 0; $j < $linelength; $j++) {
     				if ($arr1[$j] eq $arr2[$j]) { 
        				$char = $arr1[$j];
        			} else {
        				$char = '2';
        				$numtwos++;
        				$totaltwos++;
     				}
     				$genoline = $genoline . "$char "; 
 			}
 			

 			if ($numtwos == 1) {
   				$genoone = $genoline;
   				$genoline =~ tr/2/0/;
   				for ($k = 0; $k < 3; $k++) {
   					$homarray[$nhom++] = $genoline;
   				}

   				$genoone =~ tr/2/1/;
   				for ($k = 0; $k < 3; $k++) {
   					$homarray[$nhom++] = $genoone;
  	 			}
  	 			print OUTTI "2\n";
   				#$nsam++;
 			} elsif ($numtwos == 0) {
   				for ($k = 0; $k < 3; $k++) {
   					$homarray[$nhom++] = $genoline;
   				}
   				print OUTTI "1\n";
 			} else {
   				#$hetarray[$nhet++] = $genoline;
   				#$hetarray[$nhet++] = $lastline;
   				#$hetarray[$nhet++] = $line;
   				#$thet++;
   				$homarray[$nhom++] = $genoline;
   				$homarray[$nhom++] = $lastline;
   				$homarray[$nhom++] = $line;
   				print OUTTI "1\n";
 			}

 			$eo = 0;
		} else {
  			$eo = 1;
 		}

		$lastline = $line;
		
	}
}
close(IN);
	
$numtwos = 0;
if ($i > 0) {
   			$hom = $nhom/3;
			print OUTG "$hom $linelength\n";
    			$j = 0;
    			until ($j == $nhom) {
     				print OUTG "$homarray[$j]\n";
     				for ($k = 0; $k < 3; $k++) {
     					$line = $homarray[$j++];
     					$line =~ tr/ //d;
     					print OUTHS "$line\n";
     				}
   			}
   		}

$nhom = $nhet = 0;


close (OUTG);
close (OUTTI);
close (OUTHS);