#!/usr/bin/perl -w

use Cwd;

$dir = cwd();

$maxTP = 20; 

$retrywarn = 3; 

$retry = 6; 

print "***$ARGV[0]***$ARGV[1]***\n"; 

chdir "$dir/public_html/data/";

system ("cp ../index.php index.php.old"); 

$form_prep = <<'EOF';
<html>
<head>
<title>Science.Fiction.org</title>

<link rel=stylesheet href="http://science.fiction.org/style-sheet.css" type="text/css">
<LINK REL="SHORTCUT ICON" HREF="http://science.fiction.org/favicon.ico">
</head>
<body 
bgcolor=#ffffff text=#000000>
<h2>Science.Fiction.org</h2> 
by <a href="http://freebiology.org/wiki/User:Alexanderwait">Alexander (Sasha) Wait</a> and others. 

<hr>

EOF

$form_begin = <<'EOF';


<a name="UPLOAD">
<form action="upload2.php" enctype="multipart/form-data" method=post>
<!-- don't bother sending large files (we'll just reject them) -->
<INPUT type="hidden" name="MAX_FILE_SIZE" value="10000">

<p>Intervene in the Coreworld:
<BR>
<INPUT type=file name=userfile >
<BR>

 &nbsp;
<BR>
<INPUT type=submit name=Upload value=Upload>
<BR>
</form>

<h2 align=center>Change in monomer abundance over time (by type)</h2>

<table align=center>
<tr align=right>
    <td><img WIDTH=20 HEIGHT=20 src="img/cyan.png">catalytic
    <td><img WIDTH=20 HEIGHT=20 src="img/green.png">bound  
    <td><img WIDTH=20 HEIGHT=20 src="img/blue.png">free 
    <td><img WIDTH=20 HEIGHT=20 src="img/black.png">total</tr> 
<tr><td colspan=4><img WIDTH=750 HEIGHT=300 src="data/scifi-summary1.png">
</tr></table>

<br><br>
<h2 align=center>Change in polymer abundance over time (by type)</h2>

<table align=center>
<tr align=right>
    <td><img WIDTH=20 HEIGHT=20 src="img/red.png">
    <strong>Replicators</strong> 
    <td><img WIDTH=20 HEIGHT=20 src="img/black.png">others
    <td><img WIDTH=20 HEIGHT=20 src="img/yellow.png">
    <strong>Privilege consumers</strong>
    <td><img WIDTH=20 HEIGHT=20 src="img/black.png">others</tr>
<tr><td colspan=2><img WIDTH=375 HEIGHT=150 src="data/scifi-summary2a.png">
    <td colspan=2><img WIDTH=375 HEIGHT=150 src="data/scifi-summary2b.png">
</tr><tr align=right>
    <td><img WIDTH=20 HEIGHT=20 src="img/purple.png">
    <strong>Quantum users</strong> 
    <td><img WIDTH=20 HEIGHT=20 src="img/black.png">others
    <td><img WIDTH=20 HEIGHT=20 src="img/gray.png">
    <strong>None of these</strong>
    <td><img WIDTH=20 HEIGHT=20 src="img/black.png">others</tr>
<tr><td colspan=2><img WIDTH=375 HEIGHT=150 src="data/scifi-summary2c.png">
    <td colspan=2><img WIDTH=375 HEIGHT=150 src="data/scifi-summary2d.png">
</tr></table>

<br><br>
<h2 align=center>Raw data for each time point</h2>

<table align=center> 

EOF

$form_end = <<'EOF';
</table> 

<h4 align=center>Columns correspond to bars in above graphs.  The floating gnu indicates an intervention in the coreworld.</h4> 

<br><br>

<p><table align=right cellspacing="0" cellpadding="0" >
<tr><td><a href="http://science.fiction.org">
<img height="40" width="40" 
src="http://non.fiction.org/~await/img/scifi-300x300.jpg"></a>
<td><a href="http://freegardens.net">
<img height="40" width="40" 
src="http://non.fiction.org/~await/img/freegardens-300x300.jpg"></a>
</tr><tr><td colspan="2" align="center">
<a href="http://non.fiction.org/~await/alife">
<img height="20" width="80" 
src="http://non.fiction.org/~await/img/alifeboston-600x150.jpg"></a>
</tr></table><hr>

Return to <a href="http://science.fiction.org">http://science.fiction.org</a><br><em>await @ genetics.med.harvard.edu</em>
</body>
</html>

EOF

chdir "$dir/public_html/data/meta";

@files = grep {-f} glob "*.meta.qcz";

chdir "$dir/public_html/data/"; 

$maxJ = int ((scalar(@files) + $maxTP -1) / $maxTP);  
$maxI = int ((scalar(@files) + $maxJ - 1) / $maxJ); 

for ($j = 0; $j < $maxJ; $j++) {
    
    for ($i = 0; $i < $maxI; $i++) { 
    
	$k = 1 + $i * $maxJ + $j; 

	if ($k > scalar(@files)) { 
	    last; 
	}

	#perl cookbook 6.1 
	($base = $files[$k-1]) =~ s/\.meta\.qcz//;     
	
	if (-e "done/$base.i") {
	    $img = "http://non.fiction.org/~await/img/PQMARS.jpg";
	}
	else {
	    $img = "http://non.fiction.org/~await/img/SCIFI.jpg";
	}
	if ($i == 0 ) {
	    $item = '<tr><td><center>'.$k.'</center><a href="data/epoch/'.$k.
		'"><img align=left width=20 height=20 hspace=5 src="'.
		$img.'"></a>'."\n";
	}elsif ($i < $maxI-1 ) {
	    $item = '<td><center>'.$k.'</center><a href="data/epoch/'.$k.
		'"><img align=left width=20 height=20 hspace=5 src="'
		.$img.'"></a>'."\n";
	}elsif ($i == $maxI-1 ) {
	    $item = '<td><center>'.$k.'</center><a href="data/epoch/'.$k.
		'"><img align=left width=20 height=20 hspace=5 src="'.
		$img.'"></a></tr>'."\n"; 
	}else {
	    die "index out of range in form_table $!"; 	
	}
	
	unless (-e "epoch/$k" ) {
	    
	    mkdir ("epoch/$k", 0777);
	    
	}
	unless (-e "epoch/$k/meta.qcz") {
	    
	    chdir "epoch/$k"; 
	    symlink ("../../meta/$files[$k-1]", "meta.qcz");
	    chdir "$dir/public_html/data";
	}	
	unless (-e "epoch/$k/intervention.txt") {
	    
	    if (-e "done/$base.i") {
		chdir "epoch/$k";
		symlink ("../../done/$base.i", "intervention.txt");
		chdir "$dir/public_html/data";
	    }
	} 	
	unless (-e "epoch/$k/analyze.gbz") { 
	    
	    $command = 
		"tar -Ojxf meta/$files[$k-1] |".
		"cat $dir/bin/meta.gz.bz2 - |".
		"ssh -o \"compression no\" ".
		'await@club.med.harvard.edu pQmars'.
		" >epoch/$k/analyze.gbz"; 

	    $verify = 
		"bzcat epoch/$k/analyze.gbz |".
		"zcat |".
		'grep SUMMARY |'.
		'cut "-d " -f 1,2,3,5,7,9,11,13,15,17 |'.
		"diff -q $dir/bin/summary.verify -"; 


	    $try = 0; 
	    do { 
		if ($try >= $retry) { 
		    print "ABORTING: tried *** $command *** $try times\n";
		    die; 
		}
		if ($try >= $retrywarn) {
		    print "tried *** $command *** $try times\n";
		}
		$try++; 
	    } while (system($command) || system ($verify)); 

	}

	unless (-e "epoch/$k/summary.txt") { 
	    
	    $command = "bzcat epoch/$k/analyze.gbz | zcat|".
		"grep \"^G\"";
	    	    
	    if (system("$command >epoch/$k/summary.txt")) {
		print "$command\n";
		die "failed to make analysis summary $!"; 
	    }	  
      	
	    # **************************************************
	    # output genotypes for cluster analysis
	    
	    open (SUMMARY, "$command |");
	    
	    open (CLUSTER, ">epoch/$k/cluster.txt") or die $!; 

	    while (<SUMMARY>) 
	    {
		@values = split; 
		
		$found = scalar(@values); 
		
		if ( $values[1] eq "SUMMARY") 
		{
		    print CLUSTER "\n"; 
		}
		elsif ( $values[1] eq "MD5" && $found == 3) 
		{
		    print CLUSTER "\n>$values[2]\n"; 
		}
		else 
		{
		    print CLUSTER "$values[1] "; 
		}    
	    }
	    close (SUMMARY);
	    close (CLUSTER); 
 
	}

	
	unless (-e "epoch/$k/cw4x8x8x8.wrl.gz") { 
	    chdir "epoch";
	    if (system ("time $dir/bin/vrml.pl | gzip ".
			">$k/cw4x8x8x8.wrl.gz")) {
		die "failed to make vrml $!"; 
	    }
	    chdir ".."; 	    
	}



	push (@form_table, $item);  
    }
}


chdir "epoch";

$command =  'grep SUMMARY */summary.txt |sort -n |'.
    'cut -f 4,6,8,10,12,14,16,18 "-d "';

system ("$command >meta-summary.data"); 


# **************************************************

# do the rest in R! 

open(SUMMARY1, "> meta-summary1.data") or die $!; 
open(SUMMARY2a, "> meta-summary2a.data") or die $!; 
open(SUMMARY2b, "> meta-summary2b.data") or die $!; 
open(SUMMARY2c, "> meta-summary2c.data") or die $!; 
open(SUMMARY2d, "> meta-summary2d.data") or die $!; 

open(SUMMARY, "$command |");

$count = 1; 

while (<SUMMARY>) 
{
    #learning perl 7.6.1 
    @values = split;  

    $length = scalar(@values); 
    
    if ($count == 1) 
    {
	for ($i = 0; $i < $length; $i++) 
	{
	    $sums[$i] = 0; 	    
	}
    }
    if ($length ne scalar(@sums)) {
    	die "failed to parse summary.txt $!"; 
    }
    for ($i = 0; $i < $length; $i++) 
    {
	$sums[$i] += $values[$i]; 	    
    }
    #print "@values\n";
    if ($count == $maxJ) {
	for ($i = 0; $i < $length; $i++) 
	{
	    $sums[$i] = int ($sums[$i] / $count); 	    
	}

	$total1 = $sums[5] + $sums[6] + $sums[7]; 
	$total2a = $sums[0] - $sums[1]; 
	$total2b = $sums[0] - $sums[2]; 
	$total2c = $sums[0] - $sums[3];
	$total2d = $sums[0] - $sums[4];
	
	print SUMMARY1  "$sums[5] $sums[6] $sums[7] $total1\n"; 
	print SUMMARY2a "$sums[1] $total2a\n"; 
	print SUMMARY2b "$sums[2] $total2b\n"; 
	print SUMMARY2c "$sums[3] $total2c\n"; 
	print SUMMARY2d "$sums[4] $total2d\n"; 

	$count = 0; 
    }
    $count++; 
}
if (($count-1) ne 0) 
{
    for ($i = 0; $i < $length; $i++) 
    {
	$sums[$i] = int ($sums[$i] / ($count-1)); 	    
    }    
    $total1 = $sums[5] + $sums[6] + $sums[7]; 
    $total2a = $sums[0] - $sums[1]; 
    $total2b = $sums[0] - $sums[2]; 
    $total2c = $sums[0] - $sums[3];
    $total2d = $sums[0] - $sums[4];

    print SUMMARY1 "$sums[5] $sums[6] $sums[7] $total1\n"; 
    print SUMMARY2a "$sums[1] $total2a\n"; 
    print SUMMARY2b "$sums[2] $total2b\n"; 
    print SUMMARY2c "$sums[3] $total2c\n"; 
    print SUMMARY2d "$sums[4] $total2d\n"; 
 }

close (SUMMARY1); 
close (SUMMARY2a); 
close (SUMMARY2b); 
close (SUMMARY2c); 
close (SUMMARY2d);


# do the above in R 

# **********************************************************************

chdir ".."; 

system ("R CMD BATCH $dir/bin/quathena-graphics.R"); 

if (-e "new-summary1.png"  && 
    -e "new-summary2a.png" && 
    -e "new-summary2b.png" && 
    -e "new-summary2c.png" && 
    -e "new-summary2d.png"    ) 
{
    rename ("new-summary1.png",  "scifi-summary1.png")  or die $!;  
    rename ("new-summary2a.png", "scifi-summary2a.png") or die $|;  
    rename ("new-summary2b.png", "scifi-summary2b.png") or die $!;  
    rename ("new-summary2c.png", "scifi-summary2c.png") or die $|;  
    rename ("new-summary2d.png", "scifi-summary2d.png") or die $!;  
}
else 
{
    die "failed to generate images $!"; 
}
$form = "$form_prep$form_begin@form_table$form_end";

open(NFP, "> ../index.php") or die $!; 
print NFP $form or die $!; 
close(NFP) or die $!; 


