#!/usr/bin/env perl
#--------------------------------------------------------------------
#    The MB-system:	mbm_arc2grd.perl	4/21/01
#
#    Copyright (c) 2001-2023 by
#    David W. Caress (caress@mbari.org)
#      Monterey Bay Aquarium Research Institute
#      Moss Landing, California, USA
#    Dale N. Chayes 
#      Center for Coastal and Ocean Mapping
#      University of New Hampshire
#      Durham, New Hampshire, USA
#    Christian dos Santos Ferreira
#      MARUM
#      University of Bremen
#      Bremen Germany
#      
#    MB-System was created by Caress and Chayes in 1992 at the
#      Lamont-Doherty Earth Observatory
#      Columbia University
#      Palisades, NY 10964
#
#    See README.md file for copying and redistribution conditions.
#--------------------------------------------------------------------
#
# Command:
#   mbm_arc2grd
#
# Purpose:
#   Macro to convert a ArcView ASCII grid to an GMT grid file in the
#   GMT NetCDF grid format. This allows users to import the grid
#   into GMT. The grid will have the same grid interval in both
#   longitude and latitude.
#
# Basic Usage:
#   mbm_arc2grd -Iarcfile -Ogrdfile [-H -V]
#
# Author:
#   David W. Caress
#   Monterey Bay Aquarium Research Institute
#   Moss Landing, CA 95039
#   April 21, 2001
#   (at sea on the R/V Western Flyer about
#    10 km off the windward side of Oahu)
#
#
#
#

$program_name = "mbm_arc2grd";

$zname = "Unknown [unknown]";
$title = "Unknown";

# Deal with command line arguments
&Getopts('HhI:i:J:j:N:n:O:o:T:t:VvX:x:Y:y:Z:z:');
$help =     	($opt_H || $opt_h);
$ifile =    	($opt_I || $opt_i);
$projection = 	($opt_J || $opt_j) || "Geographic";
$nodata = 		($opt_N || $opt_n);
$ofile =    	($opt_O || $opt_o);
$title =     	($opt_T || $opt_t);
$verbose =  	($opt_V || $opt_v);
$xname =     	($opt_X || $opt_x);
$yname =     	($opt_Y || $opt_y);
$zname =     	($opt_Z || $opt_z);

#--------------------------------------------------------------------

# print out help message if required
if ($help)
	{
	print "\n$program_name:\n";
	print "Version: $version\n";
    print "Macro to convert an ArcView ASCII grid to a GMT  grid file in the\n";
	print "GMT NetCDF grid format. This allows users to import the grid\n";
	print "into GMT. If the grid is not in geographic coordinates (longitude \n";
	print "and latitude), then the projected coordinate system must be specified\n";
	print "using the -J option\n";
	print "\nBasic Usage: \n";
	print "\t$program_name -Iarcfile -Ogrdfile [-H -Jprojection -Nnodata -Ttitle -V -Xxname -Yyname -Zzname]\n";
	exit 0;
	}
	
# output control parameters
if ($verbose)
	{
	print "\n$program_name:\n";
	print "Input Arc ASCII grid file:                 $ifile\n";
	print "Output GMT grd (netcdf COARDS) grid file:  $ofile\n";
	print "No data value:      $nodata\n";
    print "Projection:         $projection\n";
    print "X name:             $xname\n";
    print "Y name:             $yname\n";
    print "Z name:             $zname\n";
    print "Title:              $title\n";
    print "Verbose:            $verbose\n";
	}

# check for input file
if (!$ifile)
	{
	print "\a";
	die "No input file specified\nMacro $program_name aborted\n";
	}
elsif (! -e $ifile)
	{
	print "\a";
	die "Specified input file $ifile does not exist\nMacro $program_name aborted\n";
	}
if (!$ofile)
	{
	print "\a";
	die "No output file specified\nMacro $program_name aborted\n";
	}
	
# if $nodata not specified get existing value from input file
if (! $nodata)
	{
	$nodatastring = `grep nodata_value $ifile`;
	$nodata = $nodatastring =~ /"nodata_value\s+(\S+)/;
	}

# construct the gmt grdedit control string
if ($projection == "Geographic")
	{
	if (! $xname)
		{
        $xname = "Longitude [degrees]";
		}
	if (! $yname)
		{
        $yname = "Latitude [degrees]";
		}
	$remark = "__Projection: $projection";
	}
else
	{
	if (! $xname)
		{
        $xname = "Easting [m]";
		}
	if (! $yname)
		{
        $yname = "Northing [m]";
		}
	$remark = "__Projection: $projection";
	}
$controlstring = "\"$xname/$yname/$zname/1/0/$nodata/$title/$remark\"";

# run gmt grdconvert
$cmd = "gmt grdconvert $ifile=ef $ofile -V";
if ($verbose)
	{
	print "\nRunning gmt grdconvert...\n$cmd\n";
	}
`$cmd`;

# run gmt grdedit
$cmd = "gmt grdedit $ofile -V -D$controlstring";
if ($verbose)
	{
	print "\nRunning gmt grdedit on $ofile...\n$cmd\n";
	}
`$cmd`;

exit 0;

#-----------------------------------------------------------------------
# This should be loaded from the library but its safer to
# just include it....
#
;# getopts.pl - a better getopt.pl

;# Usage:
;#      do Getopts('a:bc');  # -a takes arg. -b & -c not. Sets opt_* as a
;#                           #  side effect.

sub Getopts {
    local($argumentative) = @_;
    local(@args,$_,$first,$rest);
    local($errs) = 0;

    @args = split( / */, $argumentative );
    while(@ARGV && ($_ = $ARGV[0]) =~ /^-(.)(.*)/) {
     ($first,$rest) = ($1,$2);
     $pos = index($argumentative,$first);
     if($pos >= $[) {
         if($args[$pos+1] eq ':') {
          shift(@ARGV);
          if($rest eq '') {
              ++$errs unless @ARGV;
              $rest = shift(@ARGV);
          }
          eval "\$opt_$first = \$rest;";
         }
         else {
          eval "\$opt_$first = 1";
          if($rest eq '') {
              shift(@ARGV);
          }
          else {
              $ARGV[0] = "-$rest";
          }
         }
     }
     else {
         print STDERR "Unknown option: $first\n";
         ++$errs;
         if($rest ne '') {
          $ARGV[0] = "-$rest";
         }
         else {
          shift(@ARGV);
         }
     }
    }
    $errs == 0;
}
