#!/usr/bin/perl -w

#
#  Make Stream Package
#
#  Willem A. Schreuder
#  October 9, 2003
#

use strict;
use lib '/pm/grflib/perl';
use GetOpt;
use DBF;

#
#  Allow usage of 12p stream network
#
my $str0 = '../data0/12s.str';
if (@ARGV>0 && $ARGV[0] eq '-12p')
{
   shift @ARGV;
   $str0 = '../data0/12.str';
}
my %args = GetOpt('f:r:' , f=>$str0 , r=>'../data/reservoir.dbf');
$str0 = $args{f};
my $res = $args{r};

#
#  Check command line arguments
#
(@ARGV>0) || die "Usage: $0 <year(s)>\n";

#
#  Database of reservoir levels
#
my $dbres = DBF->open($res,'DIRECT');
$dbres->index('MONTH','N');

#
#  Snarf stream network
#
my (@str,@wsm,@trb,%res);
open(STR , "<$str0") || die "Cannot open file $str0\n";
my $hdr = <STR>;
chomp $hdr;
my ($nstr,$nseg) = split(" ",$hdr);
<STR>;
for (my $l=0;$l<$nstr;$l++)
{
   my $line = <STR>;
   chomp $line;
   $str[$l] = $line;
   (length($line)>81) && ($res{substr($line,81)}++);
}
for (my $l=0;$l<@str;$l++)
{
   my $line = <STR>;
   chomp $line;
   $wsm[$l] = $line;
}
for (my $l=0;$l<$nseg;$l++)
{
   my $line = <STR>;
   chomp $line;
   $trb[$l] = $line;
}
close(STR);
#
#  Reservoir list
#
my @res = sort keys %res;

printf "$hdr\n";
foreach my $ARGV (@ARGV)
{
   my ($yr0,$yr1) = split('-',$ARGV);
   defined($yr1) || ($yr1 = $yr0);
   #
   #  Initialize reservoir stage
   #
   my %new;
   @new{@res} = $dbres->lookup('MONTH',100*($yr0-1)+12,'N',@res);

   #
   #  Generate stream file
   #
   foreach my $yr ($yr0 .. $yr1)
   {
      foreach my $mo (1 .. 12)
      {
         #  Update end of month elevation
         my %stage;
         my %old = %new;
         @new{@res} = $dbres->lookup('MONTH',100*$yr+$mo,'N',@res);
         foreach my $res (@res)
         {
            defined($new{$res}) || die "Missing '$res'\n";
            $stage{$res} = ($old{$res}+$new{$res})/2;
         }
         #  Store streams
         printf "%10d%10d%10d %2d/%4d\n" , $nstr , -1 , -1 , $mo , $yr;
         foreach my $str (@str)
         {
            if (length($str)>81)
            {
               my $res = substr($str,81);
               printf "%s%10.3f %s\n" , substr($str,0,70) , $stage{$res} , $res;
            }
            else
            {
               print "$str\n";
            }
         }
         foreach my $wsm (@wsm)
         {
            print "$wsm\n";
         }
         foreach my $trb (@trb)
         {
            print "$trb\n";
         }
      }
   }
}
