#!/usr/bin/perl -w

#  Create Colorado groundwater input data files
#  for M&I and pipeline pumping
#
#  Willem A Schreuder
#  Apr 7, 2008

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

#  Usage
my %args = GetOpt('d:',d=>undef);
(@ARGV==1) || die "Usage: $0 <year>\n";
my $year = shift @ARGV;
my $dir = $args{d} ? $args{d} : 'co';

#
#  Model domain
#
my ($Ni,$Nj) = (165,326);
my ($X0,$Y0) = (266023,14092806);
my ($DX,$DY) = (5280,5280);
my ($X1,$Y1) = ($X0+$Nj*$DX,$Y0+$Ni*$DY);
sub off {my ($i,$j) = @_; return ($i-1)*$Nj+($j-1);}
my @ibound;
open(DAT , "<../static/02.ibound") || die "Cannot open file ../static/02.ibound\n";
foreach my $i (1 .. $Ni)
{
   my $line = <DAT>; chomp $line;
   foreach my $j (1 .. $Nj)
   {
      $ibound[off($i,$j)] = substr($line,2*($j-1),2);
   }
}
close(DAT);

#
#  Get well locations (the year does not really matter since we use only the locations)
#
my %off;
open(DAT , "<../data/co/$year.gw") || die "Cannot open file ../data/co/$year.gw\n";
#  Skip header
while (my $line = <DAT>)
{
   ($line =~ /^#/) && last;
}
#  Get locations
while (my $line = <DAT>)
{
   my ($x,$y,undef,undef,undef,undef,$rec) = split(' ',$line);
   #  Discard wells outside model domain
   ($x<$X0 || $x>$X1 || $y<$Y0 || $y>$Y1) && next;
   #  Discard wells in dead cells
   my ($i,$j) = ($Ni-int(($y-$Y0)/$DY),int(($x-$X0)/$DX)+1);
   my $off = off($i,$j);
   ($ibound[$off] == 0) && next;
   $off{$rec} = $off;
}
close(DAT);

#
#  Read M&I pumping
#
my @pump;
open(DAT , "../2000/co/2000.mi") || die "Cannot open file ../2000/co/2000.mi\n";
foreach my $i (1 .. $Ni)
{
   push @pump , split(' ',<DAT>);
}
close(DAT);
(@pump==$Ni*$Nj) || die "mi count error\n";

#
#  Add pipeline transfer pumping
#
open(DAT , "<pipelinewells.dat") || die "Cannot open file pipelinewells.dat\n";
<DAT>;
while (my $line = <DAT>)
{
   my ($rec,$pump) = split(' ',$line);
   exists($off{$rec}) || die "Unknown well $rec\n";
   $pump[$off{$rec}] += $pump;
}
close(DAT);

#
#  Save to file
#
open(DAT , ">$dir/$year.mi") || die "Cannot open file $dir/$year.mi\n";
foreach my $i (1 .. $Ni)
{
   print DAT join(" ",splice @pump , 0 , $Nj)."\n";
}
close(DAT);
