#!/usr/bin/perl -w
#
#  This program copies Nebraska canal and lateral leakage to one file
#

use strict;
my $Ni=165;
my $Nj=326;

(@ARGV>0) || die "Usage: $0 <year(s)\n";

#
#  Loop over all requested years
#
foreach my $yr (@ARGV)
{
   #  Loop over all months
   for (my $mo=1;$mo<=12;$mo++)
   {
      my $Q=0;   #  Total leakage
      my @q;     #  Cell by cell leakage
      #  Snarf canal file
      my $txt = sprintf "../data/ne/canal/cl%.2d_%d.txt" , $yr%100 , $mo;
      open(TXT , "<$txt") || die "Cannot open file $txt\n";
      <TXT>;
      for (my $l=0;$l<$Ni*$Nj;$l++)
      {
         my $line = <TXT>;
         $line =~ s/\r?\n//;
         $q[$l] += $line;
         $Q += $line;
      }
      close(TXT);
      #  Omit output if leakage is zero
      ($Q) || next;
      #  Dump output to rcc file in ne directory
      my $file = sprintf "ne/%7.2f.rcc" , $yr+$mo/100;
      open(OUT , ">$file") || die "Cannot open file $file\n";
      for(my $i=0;$i<$Ni;$i++)
      {
         print OUT join(' ',splice(@q,0,$Nj)) . "\n";
      }
      close(OUT);
   }
}
