#! /usr/bin/perl
#
#  /projects/cold_creek/grid/watershed/convert_files.pl
#
#  This Perl converts ascii grids to C binary grids.
#  This version can handle multiple directories, as for 100 m and
#  200 m resolution for the Hanford recharge project.  Filenames are assumed
#  to be the same across directories.  ASCII grid
#  files with headers are read in, and ncols, nrows, and NODATA_value
#  from the header are used in the processing.  A new ascii file without
#  the header and possibly new value for NODATA is then written.
#  This script can handle conversions for:
#  1)  integer mask            CharAsciiToBin()
#  2)  float DEM               FloatAsciiToBin()
#  3)  integer flow direction  CharAsciiToBin_FD()
#  4)  float soil depth        FloatAsciiToBin()
#  5)  integer veg type        CharAsciiToBin(), CharBinToShortBin()
#  6)  integer soil type       CharAsciiToBin(), CharBinToShortBin()
#
#  Scott Waichler, 05/03/2002
#  scott.waichler@pnl.gov
#  Battelle Pacific Northwest National Laboratory
#  "Putting technology to work.
#   Serving the needs of the nation and humanity."

# process all the files in these directories - m for mansfield
@dirs = (
#   "../test/",
  "../inputmans/",  # run this script from /projects/dhsvm/uvm/scripts/util
#  "../inputm/",
#  "/projects/cold_creek/grid/watershed/dhsvm_100m/",
);

# the files have these common endings in their names - r for ranch w for west
#@file_suffixes = ("_ranch", "_west");
@file_suffixes = ("_west");

# Filename ending for the ascii files without the
# header rows.  An example would be "mask_1-2_noh.asc".
$file_suffix_noheader = "_noh";

# yes (1) or no (0) to convert, input prefix name, output prefix name
@mask = (0, "mask", "mask");
@dem = (0, "dem", "dem");
@flowdir = (0, "flowdir", "flowdir");
@vegtype = (0, "vegtype", "vegtype");
# @soiltype = (1, "mask", "soiltypelb");
@soiltype = (0, "soil", "soil");
@dem_gw = (0, "dem_gw_10", "dem_gw_10");
@flowdir_gw = (0, "flwdir_gw", "flwdir_gw");

# for soil depth, if you want to use a uniform depth, use form
# "yes:soildepth" where soildepth is in meters, and specify the mask as input;
# otherwise, enter yes or no
#@soildepth = ("yes:2.0", "mask", "soildepth_varsoils");
@soildepth = (1, "soildpth", "soildepth_varsoils");
#@soildepth = ("no:1.0", "mask", "soildepth");

$template_C_file = "./AllConversions3_template3.c";
$final_C_file = "./AllConversions3.c";

# loop thru the directories
foreach $dir (@dirs) {

  # loop thru the filename endings
  foreach $file_suffix (@file_suffixes) {

    if ($mask[0] == 1) {
      $mask_ascii_h = $dir . $mask[1] . $file_suffix . ".asc"; # with header rows
      $mask_ascii = $dir . $mask[2] . $file_suffix . $file_suffix_noheader . ".asc";
      $mask_bin =  $dir . $mask[2] . $file_suffix . ".bin";
      ($numrows, $numcols) = write_maskfile_without_header_rows($mask_ascii_h, $mask_ascii);
    } else {
      $mask_ascii = "nofilename";
      $mask_bin =  "nofilename";

      # WARNING--HACK!:  hardwire dimensions of grid if mask not read
      $numrows = 70;
      $numcols = 76;
    }

    if ($dem[0] == 1) {
      $dem_ascii_h = $dir . $dem[1] . $file_suffix . ".asc"; # with header rows
      $dem_ascii = $dir . $dem[2] . $file_suffix . $file_suffix_noheader . ".asc";
      $dem_bin =  $dir . $dem[2] . $file_suffix . ".bin";
      ($numrows, $numcols) = write_file_without_header_rows($dem_ascii_h, $dem_ascii);
    } else {
      $dem_ascii = "nofilename";
      $dem_bin =  "nofilename";
    }

    if ($dem_gw[0] == 1) {
      $dem_gw_ascii_h = $dir . $dem_gw[1] . $file_suffix . ".asc"; # with header rows
      $dem_gw_ascii = $dir . $dem_gw[2] . $file_suffix . $file_suffix_noheader . ".asc";
      $dem_gw_bin =  $dir . $dem_gw[2] . $file_suffix . ".bin";
      ($numrows, $numcols) = write_file_without_header_rows($dem_gw_ascii_h, $dem_gw_ascii);
    } else {
      $dem_gw_ascii = "nofilename";
      $dem_gw_bin =  "nofilename";
    }

    if ($flowdir[0] == 1) {
      $flowdir_ascii_h = $dir . $flowdir[1] . $file_suffix . ".asc"; # with header rows
      $flowdir_ascii = $dir . $flowdir[2] . $file_suffix . $file_suffix_noheader . ".asc";
      $flowdir_bin =  $dir . $flowdir[2] . $file_suffix . ".bin";
      ($numrows, $numcols) = write_file_without_header_rows($flowdir_ascii_h, $flowdir_ascii);
    } else {
      $flowdir_ascii = "nofilename";
      $flowdir_bin =  "nofilename";
    }

    if ($flowdir_gw[0] == 1) {
      $flowdir_gw_ascii_h = $dir . $flowdir_gw[1] . $file_suffix . ".asc"; # with header rows
      $flowdir_gw_ascii = $dir . $flowdir_gw[2] . $file_suffix . $file_suffix_noheader . ".asc";
      $flowdir_gw_bin =  $dir . $flowdir_gw[2] . $file_suffix . ".bin";
      ($numrows, $numcols) = write_file_without_header_rows($flowdir_gw_ascii_h, $flowdir_gw_ascii);
    } else {
      $flowdir_gw_ascii = "nofilename";
      $flowdir_gw_bin =  "nofilename";
    }

    if ($vegtype[0] == 1) {
      $vegtype_ascii_h = $dir . $vegtype[1] . $file_suffix . ".asc"; # with header rows
      $vegtype_ascii = $dir . $vegtype[2] . $file_suffix . $file_suffix_noheader . ".asc";
      $vegtype_char =  $dir . $vegtype[2] . $file_suffix . ".char";
      $vegtype_bin =  $dir . $vegtype[2] . $file_suffix . ".bin";
      ($numrows, $numcols) = write_file_without_header_rows($vegtype_ascii_h, $vegtype_ascii);
    } else {
      $vegtype_ascii = "nofilename";
      $vegtype_char =  "nofilename";
      $vegtype_bin =  "nofilename";
    }

    if ($soiltype[0] == 1) {
      $soiltype_ascii_h = $dir . $soiltype[1] . $file_suffix . ".asc"; # with header rows
      $soiltype_ascii = $dir . $soiltype[2] . $file_suffix . $file_suffix_noheader . ".asc";
      $soiltype_char =  $dir . $soiltype[2] . $file_suffix . ".char";
      $soiltype_bin =  $dir . $soiltype[2] . $file_suffix . ".bin";
      ($numrows, $numcols) = write_file_without_header_rows($soiltype_ascii_h, $soiltype_ascii);
    } else {
      $soiltype_ascii = "nofilename";
      $soiltype_char =  "nofilename";
      $soiltype_bin =  "nofilename";
    }

    if ($soildepth[0] == 1) {
      $soildepth_ascii_h = $dir . $soildepth[1] . $file_suffix . ".asc"; # with header rows
      $soildepth_ascii = $dir . $soildepth[2] . $file_suffix . $file_suffix_noheader . ".asc";
      $soildepth_bin =  $dir . $soildepth[2] . $file_suffix . ".bin";
      ($numrows, $numcols) = write_file_without_header_rows($soildepth_ascii_h, $soildepth_ascii);
    } elsif ($soildepth[0] =~ m/yes:/ ) {
      # use the mask as input and subsitute all 1s with the uniform soil depth
      ($yes, $uniform_depth)  = split(":", $soildepth[0]);
      $soildepth_ascii_h = $dir . $soildepth[1] . $file_suffix . ".asc"; # with header rows
      $soildepth_ascii = $dir . $soildepth[2] . $file_suffix . $file_suffix_noheader . ".asc";
      $soildepth_bin =  $dir . $soildepth[2] . $file_suffix . ".bin";
      ($numrows, $numcols) = 
        write_uniform_soildepth_file($soildepth_ascii_h, $soildepth_ascii, $uniform_depth);
      $soildepth[0] = 1;  # set this to 1 for C program
    } else {
      $soildepth_ascii = "nofilename";
      $soildepth_bin =  "nofilename";
      $soildepth[0] = 0;
    }

    # Hash table for flags and filenames
    %convert = (
                'NUMROWS', $numrows,
                'NUMCOLS', $numcols,
                'DO_BIN_TO_ASCII', 0,
                'DO_ASCII_TO_BIN', 1,
                'DO_MASK', $mask[0],
                'DO_DEM', $dem[0],
                'DO_GW_DEM', $dem_gw[0],
                'DO_FLOWDIR', $flowdir[0],
                'DO_GW_FLOWDIR', $flowdir_gw[0],
                'DO_ARC_TO_DHSVM_FLOWDIR', 1,
                'DO_CHAR_TO_SHORT', 1,
                'DO_VEGTYPE', $vegtype[0],
                'DO_SOILTYPE', $soiltype[0],
                'DO_SOILDEPTH', $soildepth[0],
                'MASK_ASCII', $mask_ascii,
                'MASK_BIN', $mask_bin,
                'DEM_ASCII', $dem_ascii,
                'DEM_BIN', $dem_bin,
                'DEM_GW_ASCII', $dem_gw_ascii,
                'DEM_GW_BIN', $dem_gw_bin,
                'FLOWDIR_ASCII', $flowdir_ascii,
                'FLOWDIR_BIN', $flowdir_bin,
                'FLOWDIR_GW_ASCII', $flowdir_gw_ascii,
                'FLOWDIR_GW_BIN', $flowdir_gw_bin,
                'VEGTYPE_ASCII', $vegtype_ascii,
                'VEGTYPE_CHAR', $vegtype_char,
                'VEGTYPE_BIN', $vegtype_bin,
                'SOILTYPE_ASCII', $soiltype_ascii,
                'SOILTYPE_CHAR', $soiltype_char,
                'SOILTYPE_BIN', $soiltype_bin,
                'SOILDEPTH_ASCII', $soildepth_ascii,
                'SOILDEPTH_BIN', $soildepth_bin,
               );

    # open AllConversions3.c template file
    open( template_file, "<$template_C_file" ) || die "Can't open: ", $template_C_file, "\n";
    # open new AllConversions3.c file
    open( new_file, ">$final_C_file" ) || die "Can't open: ", $final_C_file, "\n";

    # read the template file one line at a time, change variable if necessary
    # then write to new input file
    while( $line = <template_file> ) {
        while ( ($key, $value) = each %convert ) {$line =~ s/$key/$value/g;}
        print new_file $line;
    }
    close( template_file );
    close( new_file );

    # compile and run AllConversions3.c
    system("gmake -f ./makefile_new");
    system("./fileconvert");

  } # end loop thru file suffixes (different watersheds)
}  # end loop thru directories (different grid resolutions)


#  Subroutines
sub write_file_without_header_rows {

  $infile = $_[0];
  $outfile = $_[1];

  # open files
  open(  infile, "<$infile" )  || die "Can't open: ", $infile, "\n";
  open( outfile, ">$outfile" ) || die "Can't open: ", $outfile, "\n";
  # get the NROWS and NCOLS info and skip the first 6 lines (the header)
  for ($i = 0; $i < 6; $i++) {
    $line = <infile>;
    @r = split(" ", $line);
    if ($r[0] =~ m/ncols/) {$numcols = $r[1];}
    if ($r[0] =~ m/nrows/) {$numrows = $r[1];}
  }
  # finish reading the infile one line at a time and write to outfile
  while( $line = <infile> ) {
      print outfile $line;
  }
  close( infile );
  close( outfile );

  return $numrows, $numcols;
} # end function write_file_without_header_rows()

sub write_maskfile_without_header_rows {

  $infile = $_[0];
  $outfile = $_[1];

  # open files
  open(  infile, "<$infile" )  || die "Can't open: ", $infile, "\n";
  open( outfile, ">$outfile" ) || die "Can't open: ", $outfile, "\n";
  # get the NROWS and NCOLS info and skip the first 6 lines (the header)
  for ($i = 0; $i < 6; $i++) {
    $line = <infile>;
    @r = split(" ", $line);
    if ($r[0] =~ m/ncols/) {$numcols = $r[1];}
    if ($r[0] =~ m/nrows/) {$numrows = $r[1];}
    if ($r[0] =~ m/NODATA/) {$nodata = $r[1];}
  }
  # finish reading the infile one line at a time and write to outfile
  while( $line = <infile> ) {
    $line =~ s/$nodata/0/g;
    print outfile $line;
  }
  close( infile );
  close( outfile );

  return $numrows, $numcols;
} # end function write_maskfile_without_header_rows()

sub write_uniform_soildepth_file {

  $maskfile = $_[0];
  $outfile = $_[1];
  $soildepth = $_[2];

  # open files
  open( maskfile, "<$maskfile" )  || die "Can't open: ", $maskfile, "\n";
  open( outfile, ">$outfile" ) || die "Can't open: ", $outfile, "\n";
  # get the NROWS and NCOLS info and skip the first 6 lines (the header)
  for ($i = 0; $i < 6; $i++) {
    $line = <maskfile>;
    @r = split(" ", $line);
    if ($r[0] =~ m/ncols/) {$numcols = $r[1];}
    if ($r[0] =~ m/nrows/) {$numrows = $r[1];}
  }
  # finish reading the maskfile one line at a time, substitute the soil depth,
  # and write to outfile
  while( $line = <maskfile> ) {
    $line =~ s/1/$soildepth/g;
    print outfile $line;
  }
  close( maskfile );
  close( outfile );

  return $numrows, $numcols;
}  # end function write_uniform_soildepth_file()


# end of script


