#!/usr/bin/perl -w
# Modified version of dynamvinv2
# Creates table of number of soundings that reach any particular height
# Nov 2006
#
# Remarks to original dynaminv2 follow #
# generate html to display an inventory table
# this program is called from within an shtml document
# it does not work well if called directly from elsewhere. SEE Next paragraph!!
#
# Feb 2006
# Due to changes to the web server and the actual directory our pages reside,
# changes were made to this program to use relative paths instead of absolute ones
# which did not make sense. The program must now run unrelated to the way it is called:
# either from the web or from a terminal. Also,...
#
# A rutine will be added to link the number in the inventory table to a html document
# created on-the-fly. This document will show the list of WIN files for the month 
# selected and by clicking on one list item will display the sounding.
#
#anio = qw(year02 year03);
@anio = qw(year97 year98 year99 year00 year01 year02 year03 year04 year05 year06);
@monthseq= qw(jan feb mar apr may jun jul aug sep oct nov dec);
@monthfst= qw(J F M A M J J A S O N D);
@stncountry = qw(P01 me P02 me P03 me P55 me P56 me P57 me P58 me P59 me BT me CA me CN me CH me DU me GY me HB me IM me JI me LP me LE me LR me MA me SJ me SR me TE me P04 ni P05 cr P06 cr P07 pa PLS pa P08 co KBQ co KPQ co KGB co KAP co KTQ co KUA co VIA ve VGD ve P60 ve P62 ve P80 ve P00 ec P10 ec P11 ec P12 ec P18 ec P24 ec P13 pe P14 pe P15 pe P16 pe P17 pe P21 pe P26 pe P27 pe P28 pe P29 pe PQT pe PTU pe BCS br BDO br BRB br BVI br P20 bo P70 bo P71 bo P72 bo P73 bo P74 bo P77 bo P30 py P32 py CBA ar CHA ar JVG ar PAM ar PAR ar SIS ar SGO ar TOS ar GB us LH us SC us);
@stnnames = qw(
 P00 Porto_viejo
 P01 Salina_Cruz
 P02 Puerto_Madero
 P03 Frontera
 P04 Managua
 P05 Liberia
 P06 Cocos
 P07 David
 KBQ Barranquilla
 KPQ Puerto_Salgar
 KGB Cali
 KAP Apiay
 KTQ Tres_Esquinas
 KUA Marandua
 P08 Cartagena
 P10 Esmeraldas
 P11 Guayaquil
 P12 Galapagos
 P13 Piura
 P14 Tumbes
 P15 Trujillo
 P16 Ancon2
 P17 Iquitos
 P18 Ancon
 P20 Santa_Cruz
 P21 Chiclayo
 P24 Izobamba
 P26 Pucallpa
 P27 Ica
 P28 Puno
 P29 Arequipa
 PQT Iquitos
 PTU Puerto_Maldonado
 P30 Asuncion
 P32 Estigarribia
 P55 Puerto_Penasco
 P56 Topolobampo
 P57 Tampico
 P58 Cd_Carmen
 P59 Veracruz
 VIA Isla_de_Aves
 VGD Guasdualito
 P60 San_Fernando
 P62 Cd_Bolivar
 P80 Maracay
 P70 Cobija
 P71 Trinidad
 P72 La_Paz
 P73 Robore
 P74 Uyuni
 P75 Cochabamba
 P76 Sucre
 P77 Villamontes
 PAM Pampa_Guanacos
 PAR Parana
 SIS Resistencia
 SGO Santiago_Estero
 JVG Joaquin_V_Glez
 TOS Tostado
 CBA Cordoba
 CHA Chamical
 BCS CruzeiroDoSul
 BDO Dourados
 BRB Rio_Branco
 BVI Vilhena
 CLL Vallenar
 CCF Calama
 PLS Los_Santos
 GB  Gila_Bend
 LH  Lake_Havasu
 SC  Silver_City
 BT  Bahia_Tortugas
 CA  Catavina
 CN  Constitucion
 CH  Choix
 DU  Durango
 GY  Empalme
 HB  Huatabampo
 IM  Isla_Maria
 JI  Jimenez
 LP  La_Paz
 LE  Lerdo
 LR  Loreto
 MA  Matehuala
 SJ  San_Jose_Cabo
 SR  Santa_Rosalia
 SC  Silver_City
 TE  Tesopaco);
#
@stndirs = qw(
 P00 00
 P01 01
 P02 02
 P03 03
 P04 04
 P05 05
 P06 06
 P07 07
 P08 08
 KBQ kbq
 KPQ kpq
 KGB kgb
 KAP kap
 KTQ ktq
 KUA kua
 P10 10
 P11 11
 P12 12
 P13 13
 P14 14
 P15 15
 P16 16
 P17 17
 P18 18
 P20 20
 P21 21
 P24 24
 P26 26
 P27 27
 P28 28
 P29 29
 PQT pqt
 PTU ptu
 P30 30
 P32 32
 P55 55
 P56 56
 P57 57
 P58 58
 P59 59
 VIA via
 VGD vgd
 P60 60
 P62 62
 P70 70
 P71 71
 P72 72
 P73 73
 P74 74
 P75 75
 P76 76
 P77 77
 P80 80
 PAM pam
 PAR par
 SIS sis
 SGO sgo
 JVG jvg
 TOS tos
 CBA cba
 CHA cha
 BCS bcs
 BDO bdo
 BRB brb
 BVI bvi
 CLL cll
 CCF ccf
 PLS lsantos
 GB  gb
 LH  lh
 SC  sc
 BT bt
 CA ca
 CN cn
 CH ch
 DU du
 GY gy
 HB hb
 IM im
 JI ji
 LP lp
 LE le
 LR lr
 MA ma
 SJ sj
 SR sr
 TE te);
@countrynam = qw(me MEX ni NICARAGUA cr COSTA-RICA pa PANAMA co COLOMBIA ve VENEZUELA br BRAZIL ec ECUADOR pe PERU bo BOLIVIA py PARAGUAY ar ARGENTINA us USA al Network);
@iniyear = qw(me 1997 ni 1997 cr 1997 pa 1997 co 1997 ve 2001 br 2002 ec 1997 pe 1997 bo 1998 py 1999 ar 2002 us 2004 al 1997);
@endyear = qw(me 2006 ni 2006 cr 1999 pa 2001 co 2006 ve 2006 br 2003 ec 2005 pe 2006 bo 2004 py 2005 ar 2003 us 2004 al 2006);
#
%stncountry = @stncountry;
%stnnames = @stnnames;
%stndirs = @stndirs;
%countrynam = @countrynam;
%iniyear = @iniyear;
%endyear = @endyear;
#
if ($ARGV[0]) {
   $mycountry = $ARGV[0];
}
else {
   $mycountry = "al";
}
$currmo=`date +"%m"`;
$currye=`date +"%Y"`;
chomp($currmo);
chomp($currye);
#
#
#$monthnam = $monthseq[$currmo - 1];
# html start and ending tags in the calling shtml document
print <<Html_header_lines;
 <head>
 <meta http-equiv="charset" content="iso-8859-1">
 <title>PACS-SONET Data Inventory Update</title>
 </head>
 <body bgcolor="#ffffff">
 <FONT SIZE=5><P ALIGN="CENTER">Pilot balloon data / $countrynam{$mycountry}</P></FONT>
 <CENTER><TABLE BORDER=0 CELLSPACING=5 CELLPADDING=1 WIDTH=50%>
 <TR><TD width=100% COLSPAN=4 ALIGN="CENTER"><FONT SIZE=4>Number of observations per month</FONT></TD>
 <TR><TD width=25% bgcolor="#ffff00" align="center">1-14</td>
 <TD width=25% bgcolor="#00ff00" align="center">15-29</td>
 <TD width=25% bgcolor="#00ffff" align="center">30-44</td>
 <TD width=25% bgcolor="#a0d0ff" align="center"> &gt;= 45</td>
 </tr></table></center>
 <center><table border cellpadding=1 cellspacing=1>
Html_header_lines
#$somthing = `ls /`;
#chomp($somthing);
#print $somthing;
columnhea(1);
foreach $site (@stncountry) {
      if ($stncountry{$site} && $stncountry{$site} eq $mycountry) {
         countobs();
      }
      elsif ($stncountry{$site} && $mycountry eq "al") {
         countobs();
      }
}
columnhea(2);
print "</table></center>";
print "</body>";
print "\n";
$freq{0} = 0;
#Write statistics for all
      open(VSHEIGHT, ">obs-hght_all") || die "No tiene caso sequir\n";
      foreach (%freq) {
          if ($freq{$_}) {printf VSHEIGHT "%10.3f %6d\n",$_, $freq{$_};}
          #$freq{$_} = 0;
      }
      close(VSHEIGHT);
#
sub countobs {
#
$inventdir = `pwd`;
   if (-d "../data/$stncountry{$site}/$stndirs{$site}") {
      #inistat($site);
      inirow($site);
      chdir("../data/$stncountry{$site}/$stndirs{$site}");
#     foreach $year ( @anio ) {
      for($iyear = $iniyear{$mycountry}; $iyear <= $endyear{$mycountry}; $iyear++) {
         $a2o = substr($iyear,2,2);
         $year = "year" . $a2o;
         if (-d "$year") {
            chdir($year);
            foreach $mes ( @monthseq ) {
               if(-d "$mes$a2o") {
                  $count=0;
                  foreach (<$mes$a2o/*.WIN>) {
                     open(WINFILE, $_) || print "No puedo con $_\n";
                     <WINFILE>;
                     <WINFILE>;
                     chomp;
                     while(<WINFILE>) {
                        chomp;
                        @alinea=split;
                        if($#alinea > 0 && $alinea[0] != 0 && $alinea[1] != 0 && $alinea[1]/$alinea[0]< 7){ $alinea[0]=$alinea[0]/60.;}
                        if($#alinea > 0 && $alinea[0] > 0 && $alinea[0] < 100) {
                           $timestr=sprintf("%6.3f", $alinea[0]);
                           if($freq{$timestr}) {
                              $freq{$timestr} = 1 + $freq{$timestr};
                           }
                           else {$freq{$timestr}=1;}
                        }
                     }
                     close(WINFILE);
                     $count++;
                  }
                  $totobs{$mes . $a2o} = $totobs{$mes . $a2o} + $count;
                  if ($count > 0) { $totstn{$mes . $a2o}++;}
                  numobs($count,"$stndirs{$site}/$year/$mes$a2o");
                  #nobsplus($count,"$stndirs{$site}/$year/$mes$a2o");
               }
               else {
                  nodatamo();
               } #endif
            } #endforeach
            chdir("../"); #one level up from year directory
         } #endif $year directory exists 
         else {
            nodatayr();
         } #endelse
      } #endfor years
      chdir("../../../inventories"); #up to station to country to data to inventories
      # Print number of observations vs height
      #open(VSHEIGHT, ">obs-hght_$site") || die "No tiene caso sequir\n";
      #foreach (%freq) {
      #    if ($freq{$_}) {printf VSHEIGHT "%10.3f %6d\n",$_, $freq{$_};}
      #    $freq{$_} = 0;
      #}
      #close(VSHEIGHT);
      endrow($site);
      #endstat();
   } #endif site is a directory
} #end subcountobs
#
sub columnhea {
if($_[0] == 1) {
#
   foreach $year (@anio) {
      $a2o = substr($year,4,2);
      foreach $mes (@monthseq) {
         $totobs{$mes . $a2o} = 0;
         $totstn{$mes . $a2o} = 0;
      }
   }
#
   print "<tr><th></th>";
   for($iyear = $iniyear{$mycountry}; $iyear <= $endyear{$mycountry}; $iyear++) {
    print "<th colspan=12 align=center>$iyear</th>";
   }
   print "</tr>\n";
}
#
print "<tr><td></td>";
for($iyear = $iniyear{$mycountry}; $iyear <= $endyear{$mycountry}; $iyear++) {
   foreach $mes (@monthfst) {
      print "<td>$mes</td>";
   }
}
print "<td>&nbsp;</td></tr>\n";

if($_[0] == 2) {
#
$lastup = `date +"%m/%d/%Y"`;
$grandtot = 0;
print "<tr><td>Obs<br>Stns</td>";
for($iyear = $iniyear{$mycountry}; $iyear <= $endyear{$mycountry}; $iyear++) {
   $a2o = substr($iyear,2,2);
   foreach $mes (@monthseq) {
      if($totobs{$mes . $a2o} > 0) {
         print "<td><font size=2>$totobs{$mes . $a2o}<br>$totstn{$mes . $a2o}</font></td>";
      }
      else {
         print "<td>&nbsp;</td>";
      }
      $grandtot = $grandtot + $totobs{$mes . $a2o};
   }
}
print "<td>$grandtot Obs<br>Stns</td></tr>\n";
#
print "<tr><th></th>";
for($iyear = $iniyear{$mycountry}; $iyear <= $endyear{$mycountry}; $iyear++) {
    print "<td colspan=12 align=center>$iyear</td>";
}
print "<td>Last updated: $lastup</td></tr>\n";
}
}

sub inirow {
print "<tr><td><font size=2>$_[0]&nbsp;$stnnames{$_[0]}</font></td>\n";
}
sub endrow {
print "<td><font size=2>$_[0]&nbsp;$stnnames{$_[0]}&nbsp;($countrynam{$stncountry{$_[0]}})</font></td></tr>\n";
}
sub numobs {
$country=$stncountry{$site};
if($_[0] > 44) {
   $color = "#a0d0ff";
}
elsif($_[0] > 29) {
   $color = "#00ffff";
}
elsif($_[0] > 14) {
   $color = "#00ff00";
}
elsif($_[0] > 0) {
   $color = "#ffff00";
}
else {
   $color = "#ffffff";
}
print "<td bgcolor=\"$color\"><a href=\"/cgi-bin/lst_pacs.cgi/$country/$_[1]\"><font size=2>$_[0]</font></a></td>\n";
}
sub nodatamo {
print "<td>&nbsp;</td>";
}
sub nodatayr {
   for ($imonth = 1; $imonth <= 12 ; $imonth++) {
     nodatamo();
   }
}
sub noyear {
#   do nothing
}

sub inistat {
print "first time at inistat?\n";
open(STATFILE,">stat_$_[0]") || die "Imposible abrir $_[0]\n";
print STATFILE "Something\n";
}

sub endstat {
close(STATFILE) || die "Impossible to close STATFILE\n";
}