#!/usr/bin/perl -w
# program to activate a subbasin within a whole soil file
# AWW-102804
# inputs:  old soil file
#          new soil file name
#          lat lon file for subbasin to activate
#          [optional: lat lon file for subbasin to DEactivate]

if(@ARGV == 3) {
  print @ARGV . " arguments found\n";
  open(OLDSOIL, "<$ARGV[0]") or die "can't open oldsoil file $ARGV[0]: !$\n";
  open(NEWSOIL, ">$ARGV[1]") or die "can't open newsoil file $ARGV[1]: !$\n";
  open(ACT_LL,  "<$ARGV[2]") or die "can't open active latlon file $ARGV[2]: !$\n";
} elsif (@ARGV == 4) {
  print @ARGV . " arguments found\n";
  open(OLDSOIL, "<$ARGV[0]") or die "can't open oldsoil file $ARGV[0]: !$\n";
  open(NEWSOIL, ">$ARGV[1]") or die "can't open newsoil file $ARGV[1]: !$\n";
  open(ACT_LL,  "<$ARGV[2]") or die "can't open active latlon file $ARGV[2]: !$\n";
  open(INACT_LL,"<$ARGV[3]") or die "can't open INactive latlon file $ARGV[3]: !$\n";
} else {
  die "Usage: activate_basin.pl <oldsoilfile> <newsoilfile> <active latlons> [<INactive lonlats>]\n";
}

$n=0;
print "reading active lat lons...\n";
while($line = <ACT_LL>) {
  ($lat[$n],$lon[$n]) = split(" ",$line);
  $n++;
}
close(ACT_LL);

if(@ARGV == 4) {
  $n=0;
  print "reading INactive lat lons...\n";
  while($line = <INACT_LL>) {
    ($no_lat[$n],$no_lon[$n]) = split(" ",$line);
    $n++;
  }
  close(INACT_LL);
}

$row = 0;
while($line = <OLDSOIL>) {
  print "reading soil file row $row ...\n";
  ($flag,$cellno,$lats,$lons,@tmp) = split(" ",$line);

  $flag = $found_inact = 0;

  # check inactive (if specified)
  if(@ARGV == 4) {
    for($i=0;$i<@no_lat;$i++) {
      if($no_lat[$i]==$lats && $no_lon[$i]==$lons) {
        $found_inact = 1;  # flag stays at 0
        last;
      }
    }
  }
  if($found_inact == 0) {
    # set active if cell latlon in active latlon list
    for($i=0;$i<@lat;$i++) {
      if($lat[$i]==$lats && $lon[$i]==$lons) {
        $flag = 1;
        last;
      }
    }
  }

  # write out
  printf NEWSOIL "%d %d %.5f %.5f", $flag,$cellno,$lats,$lons;
  for($f=0;$f<@tmp;$f++) {
    printf NEWSOIL " %s", $tmp[$f];
  }
  printf NEWSOIL "\n";
  $row++;
}

close(OLDSOIL);
close(NEWSOIL);
