#!/usr/bin/perl
use CGI qw/:standard/;
use MicModule;

### universal overview table creation script for 
#   filenames   P_S_Y_M_ST_TYPE (lidar (works) ,surfobs,create,synthesis)
#   filenames V_S_P_Y_M_ST_TYPE (retro (works) )

# called by : 
# makealltables.pl ctyp=lidar
# makealltables.pl ctyp=retro
# makealltables.pl ctyp=surfobs
# makealltables.pl ctyp=create

$q = new CGI;
$ctyp = $q->param('ctyp');

## switch to activate other web servers with other 
## directories
$machine="dataipsl";

$httpbase='http://dataipsl.ipsl.jussieu.fr/AEROCOM/DATA/';
$httpbasen='http://dataipsl.ipsl.jussieu.fr/AEROCOM/DATA/';
$dirperl='/cgi-bin/AEROCOM/';
$dirunixbase = '/bipbip/AEROCOM/';

if ( $machine eq 'boulimix' ) {
    $httpbase='http://boulimix/w3data/schulz/AEROCOM0/';
    $dirperl='/cgi-bin/w3data/schulz/';
    $dirunixbase = '/home/aerocom0/';
}

if ( $ctyp eq 'inca_atlas' ) {$dirperl=$dirperl.'inca_work/';}
elsif ( $ctyp eq /synthesis/ ) {$dirperl=$dirperl.$ctyp.'/';}
elsif ( $ctyp eq 'lidar' ) {$dirperl=$dirperl.'aerocom/';}
else {($dirperl=$dirperl.$ctyp.'/');}

$httpmodels=$httpbase;
$dirdoc = $dirunixbase . 'INTERFACE_DOC';

    if  ( $ctyp =~ /lidar|create|retro|synthesis|surfobs/ )  { 
	$httpmodels = $httpbase . uc($ctyp).'/';
	$dirunix = $dirunixbase . uc($ctyp).'/';
	$dirdoc = $dirunixbase . 'INTERFACE_DOC/'.uc($ctyp).'/';
    }	

#### [V][S][P][Y][M][ST][TYP].png
@vlist0 = ();
@slist0 = ();
@plist0 = ();
@ylist0 = ();
@mlist0 = ();
@stlist0 = ();
@typlist0 = ();

### import list from interface module
@rlist = ::MicModule::psr($ctyp,"dummy","dummy",$dirunix);
#if  ($ctyp eq 'lidar') {
#    @rlist = ('LSCE');}

@table = ([]);
while ($rlist > @table){
    @table = (@table,([]));
}


# loop over directory list
for($r=0; $r<@rlist; $r++) {
    chdir  $dirunix . $rlist[$r] . "/plots"  || next ;
    print  $dirunix . $rlist[$r] . "/plots \n" ;

    @vlist = ();
    @slist = ();
    @plist = ();
    @ylist = ();
    @mlist = ();
    @stlist = ();
    @typlist = ();

# numerote the name fractions from original filename
# as seperated by an underscore or point
if  ($ctyp eq 'retro') {
    $argv1  = 0;  
    $argv2  = 1;
    $args   = 2;
    $argp   = 3;
    $argy   = 4;
    $argm   = 5;
    $argst  = 6;
    $argtyp = 7;
}
else {
    $argv1  = 8;  
    $argv2  = 8;
    $args   = 1;
    $argp   = 0;
    $argy   = 2;
    $argm   = 3;
    $argst  = 4;
    $argtyp = 5;
}


# getting the overall file list
    my @flist = ();
    if ( $ctyp =~ /retro|surfobs|create/) {
	@flist = glob("*.png");}

    else {
	my @month =('mALLYEAR','m01','m02','m03','m04','m05','m06','m07','m08','m09','m10','m11','m12','m*d');
	for($i=0; $i<14; $i++) {
	    $choi='*_'.$month[$i].'_*';
	    @flist=(@flist,glob ($choi));}
    }



# loop over file list
    for($i=0; $i<@flist; $i++) {
	
# cutting the filename into pieces, stored in array @a
	my @a = split /[\_\.]/, $flist[$i];

#### [V][S][P][Y][M][ST][TYP].png 
	$vlist[$i] = $a[$argv1].'_'.$a[$argv2];
	$slist[$i] = $a[$args];
	$plist[$i] = $a[$argp];
	$ylist[$i] = $a[$argy];
	$mlist[$i] = $a[$argm];
	$stlist[$i] = $a[$argst];
	$typlist[$i] = $a[$argtyp];

    }
    @vlist0 = ( @vlist0 , @vlist );
    @slist0 = ( @slist0 , @slist );
    @plist0 = ( @plist0 , @plist );
    @ylist0 = ( @ylist0 , @ylist );
    @mlist0 = ( @mlist0 , @mlist );
    @stlist0 = ( @stlist0 , @stlist );
    @typlist0 = ( @typlist0 , @typlist );

}

my %count =();
@vlist0 = sort (grep { ++$count{$_} < 2 } @vlist0);
my %count =();
@slist0 = sort (grep { ++$count{$_} < 2 } @slist0);
my %count =();
@plist0 = sort (grep { ++$count{$_} < 2 } @plist0);
my %count =();
@ylist0 = sort (grep { ++$count{$_} < 2 } @ylist0);
my %count =();
@mlist0 = sort (grep { ++$count{$_} < 2 } @mlist0);
my %count =();
@stlist0 = sort (grep { ++$count{$_} < 2 } @stlist0);
my %count =();
@typlist0 = sort (grep { ++$count{$_} < 2 } @typlist0);


if (grep { /ALLYEAR/ } @mlist0)          {@mlist00=(@mlist00,'annual')};
if (grep { /[0-1][0-9]/ } @mlist0) {@mlist00=(@mlist00,'monthly')};
if (grep { /m..d/ } @mlist0)        {@mlist00=(@mlist00,'daily')};
if (grep { /AMJ|JAS|OND|JFM/ } @mlist0)        {@mlist00=(@mlist00,'seasonal')};
@mlist0 = @mlist00;

if ($ctyp =~ /surfobs|create/ ){@stlist0=()}

print "typlist - ", @typlist0," \n";
print "slist - ", @slist0," \n";
print "plist - ", @plist0," \n";
print "stlist - ", @stlist0," \n";
print "ylist - ", @ylist0," \n";
print "mlist - ", @mlist0," \n";



# checking for availaibily of image    
# looping over all species / printing one file per species
for($s=0; $s<@slist0; $s++) { 
for($y=0; $y<@ylist0; $y++) { 
for($m=0; $m<@mlist0; $m++) { 
for($st=0; $st<=@stlist0; $st++) { 

    
    @tablesum=();

    for($r=0; $r<@rlist; $r++) {
	chdir $dirunix . $rlist[$r] . "/plots" || next;
	my @flist0=();
	if ( $ctyp eq 'retro') {
	    $tt = '*_'.$slist0[$s].'*'.$ylist0[$y].'_*_'.$stlist0[$st].'*';
	    @flist0=glob ($tt);
	}
	elsif ($ctyp =~ /surfobs|create/ ) {
	    $tt = '*_'.$slist0[$s].'_'.$ylist0[$y].'_*';
	    @flist0=glob ($tt);
	}
	else {
	    $tt = '*_'.$slist0[$s].'_'.$ylist0[$y].'_*_'.$stlist0[$st].'*';
	    @flist0=glob ($tt);
	}


	for($typ=0; $typ<@typlist0; $typ++) {
	    for($p=0; $p<@plist0; $p++) {
		
		$tt="";

		if ( $ctyp =~ /retro/ ) {
		    $tt = $slist0[$s].'_'.$plist0[$p].'_'.$ylist0[$y].'_.+_'.$stlist0[$st].'_'.$typlist0[$typ]}
		elsif ($ctyp =~ /surfobs|create/ ) {
		    $tt = $plist0[$p].'_'.$slist0[$s].'_'.$ylist0[$y].'_.+_'.$typlist0[$typ]}
		else {
		    $tt = $plist0[$p].'_'.$slist0[$s].'_'.$ylist0[$y].'_.+_'.$stlist0[$st].'_'.$typlist0[$typ]}

		@ff=();
		if ($mlist0[$m] eq 'annual') {
		    @ff = grep { /$tt/ } (grep {/_mA/} @flist0) }
		if ($mlist0[$m] eq 'monthly') {
		    @ff = grep { /$tt/ } (grep {/_m[0-1][0-9]_/} @flist0)}
 		if ($mlist0[$m] eq 'daily') {
		    @ff = grep { /$tt/ } (grep {/m..d/} @flist0)}
 		if ($mlist0[$m] eq 'seasonal') {
		    @ff = grep { /$tt/ } (grep {/AMJ|JAS|OND|JFM/} @flist0)}

		$cellnum=$typ*@plist0+$p;
		if (@ff>0) {
		    $table[$cellnum][$r] = 1;
		    $tablesum[$cellnum]=$tablesum[$cellnum]+1;
		}
		else {
		    $table[$cellnum][$r] = 0;
		    $tablesum[$cellnum]=$tablesum[$cellnum]+0;
		}

	    }
	}
    }

######################## printing header

    chdir $dirdoc;
    
    if ($ctyp =~ /surfobs|create/ ) {
	$name=$slist0[$s].'_'.$ylist0[$y].'_'.$mlist0[$m].'.html'}
    else {$name=$slist0[$s].'_'.$ylist0[$y].'_'.$mlist0[$m].'_'.$stlist0[$st].'.html';}

    $outfile = ">".$name;
    open (OUT , $outfile); print OUT "";
    $outfile2 = ">>".$name;
    open (OUT , $outfile2);

    print OUT "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01 Transitional//EN'>
<html>
<head>
<title>OVERVIEW TABLE ",$ctyp,"-interface ",$slist0[$s],"</title>
<meta http-equiv='Content-Type' content='text/html; charset=iso-8859-1'>
</head>
<body>";

if ($ctyp =~ /surfobs|create/ ) {
print OUT '<script language="Javascript" type= "text/javascript">
<!-- hide script from older browsers
function chgTable() {
          spe=eval ("document.myForm.SLIST" )
          yea=eval ("document.myForm.YLIST"  )
          per=eval ("document.myForm.MLIST"  )
          s=spe.selectedIndex
          y=yea.selectedIndex
          m=per.selectedIndex
          b = (    spe.options[s].value 
                   + "_" + yea.options[y].value 
                   + "_" + per.options[m].value 
                   + ".html") 
          window.location = b
}
// end hiding -->
</script>';}
else {
print OUT '<script language="Javascript" type= "text/javascript">
<!-- hide script from older browsers

function chgTable() {
          spe=eval ("document.myForm.SLIST" )
          sta=eval ("document.myForm.STLIST"  )
          yea=eval ("document.myForm.YLIST"  )
          per=eval ("document.myForm.MLIST"  )

          s=spe.selectedIndex
          st=sta.selectedIndex
          y=yea.selectedIndex
          m=per.selectedIndex

          b = (    spe.options[s].value 
                   + "_" + yea.options[y].value 
                   + "_" + per.options[m].value 
                   + "_" + sta.options[st].value 
                   + ".html") 

          window.location = b
          
}
// end hiding -->
</script>';}


print OUT "<table  border='0' cellspacing='0' cellpadding='0'>
  <tr>
    <td valign='middle'>";

if ( $ctyp eq 'retro') {
    print OUT "<img src='../../RETRO/INCANMHC_SS40/plots/INCANMHC_SS40_",
    $slist0[$s],"_VMR_1960_JAS_WORLD_MAPSUR.png'>"}
elsif ($ctyp eq 'lidar') {
    print OUT "<img src='".$httpmodels."LSCE/plots/EC355_",
    $slist0[$s],"_",$ylist[$y],"_mALLYEAR_",$stlist[$st],"_",$typlist0[0],".ps.png'>"}

print OUT "
    </td>
    <td  align ='center'><p><strong><em>Overview of availability of ";

if ($ctyp =~ /lidar|retro/) {
    print OUT "images for<br><font size='5' color='#FF0000'>", $slist0[$s],"-",$ylist0[$y],"-",$mlist0[$m],"-",$stlist0[$st];}
else  {print OUT "images for<br><font size='5' color='#FF0000'>", $slist0[$s],"-",$ylist0[$y],"-",$mlist0[$m];}

print OUT "</font><br>
    on ",uc($ctyp)," WEB INTERFACE</em></strong><br>
        <br>

        </p>
      <a href='javascript:history.back()'>&lt;- BACK history</a><br>
      <a href=",$dirperl,$ctyp,"_annualrs.pl >&lt;- BACK to interface default</a><br><br>
      Choose overview table for another species - year - period"; 
    if ($ctyp eq 'lidar'){
	print OUT "- station:";}

    print OUT '<form method="POST" action=",$dirperl,$ctyp,"_annualrs.pl" name="myForm">';

    $ns="chgTable()";

    print OUT $q->popup_menu(-name=>'SLIST',-values=>\@slist0,-default=>$slist0[$s],-override=>1,-onChange=>$ns,-onKeyup=>$ns);
    print OUT $q->popup_menu(-name=>'YLIST',-values=>\@ylist0,-default=>$ylist0[$y],-override=>1,-onChange=>$ns,-onKeyup=>$ns);
    print OUT $q->popup_menu(-name=>'MLIST',-values=>\@mlist0,-default=>$mlist0[$m],-override=>1,-onChange=>$ns,-onKeyup=>$ns);

    if ($ctyp =~ /lidar|retro/) {
	print OUT $q->popup_menu(-name=>'STLIST',-values=>\@stlist0,-default=>$stlist0[$st],-override=>1,-onChange=>$ns,-onKeyup=>$ns);}
    print OUT "<br><br> Graph type explanations: <br>",
       $q->popup_menu(-name=>'TYPLIST',-values=>\@typlist0,-labels=>\%::MicModule::typxlabelhash,-override=>1);
    print OUT "<br><br> Parameter explanations: <br>",
       $q->popup_menu(-name=>'PLIST',-values=>\@plist0,-labels=>\%::MicModule::pxlabelhash,-override=>1);
    print OUT "
      </td>
  </tr>
</table>
<br>";


########################################
# print header of table

#     <table width=",102+(@rlist)*101," border='1' cellspacing='0' cellpadding='2' bordercolor='#0099FF'>
    print OUT "
     <table border='1' cellspacing='0' cellpadding='0' bordercolor='#0099FF'>
    <tr>
    <td>&nbsp;</td>
    <td colspan='",@rlist+0,"' bgcolor='#0099FF'> 
    <font size='-3' face='Arial, Helvetica, sans-serif'><strong>
    Model Names abbreviated</font></td>
    </tr>
    <tr align='center' bgcolor='#99FFFF'>
    <td width='100'><font size='-3' face='Arial, Helvetica, sans-serif'><strong>Type_Parameter</font></td>";

    for($r=0; $r<@rlist; $r++) {
	print OUT "
    <td width='100'><font size='-3' face='Arial, Helvetica, sans-serif'><strong>",$rlist[$r],"</font></td>"    }		   
    print OUT  "</tr>";
    
# print row information


    $counter=0;
    for($typ=0; $typ<@typlist0; $typ++) {
	$newtyp=1;
	for($p=0; $p<@plist0; $p++) {
	    $cellnum=$typ*@plist0+$p;
	    if ($tablesum[$cellnum] < 1) {next; }
	    $counter=$counter+1;
	    if ($counter>20) {
		$counter=0;
		print OUT "
            <tr align='center' bgcolor='#99FFFF'>
            <td>&nbsp;</td>";
	    
		for($r=0; $r<@rlist; $r++) {
		    print OUT "
                    <td><font size='-3' face='Arial, Helvetica, sans-serif'><strong>",
         	    $rlist[$r],"</td>";
        	}	   
        	print OUT  "</tr>";
	    }
	    

# start printing row
	    $rowname = $typlist0[$typ].'_'.$plist0[$p];
	    print OUT "
            <tr><td align='center'";
	    if ($newtyp==1){
		print OUT "bgcolor='#33BB33'";
		$newtyp=0;}
	    print OUT ">
            <font size='-3' face='Arial, Helvetica, sans-serif'><strong>",
		$rowname,"</td>";

# print table cell info f(cellnum)
	    for($r=0; $r<@rlist; $r++) {
		if ($table[$cellnum][$r]==1 ) {
		    print OUT "<td align='center' bgcolor='#00FF00'>    
              <font size='-3' face='Arial, Helvetica, sans-serif'><strong>x</td>";
		}
		else {print OUT "<td bgcolor='#FFFFCC'>&nbsp;</td>";}
	    }
      	    print OUT "</strong></font></tr>";
	}
    }

print OUT "</table>";
close OUT;
}
}
}
}
