#!/bin/perl

# Program to convert GeoVu grids to GMT short integer grids.
# Geoffrey Ely   3/31/97

if( $#ARGV != 0 ) { print "usage: gv2gmt <filename base>\n"; exit 0; }
$file = $ARGV[0];
$header_file = "$file.hdr";
$binary_file = "$file.bin";
$gmt_grd_file = "$file.grd";

printf STDERR "reading header file: %s\n", $header_file;
open( HFILE, $header_file );
while( <HFILE> ) {
  chop; chop;
  if    ( /^number_of_columns.*= ([-.0-9]+)/ )	{ $nx = $1; }
  elsif ( /^number_of_rows.*= ([-.0-9]+)/ )	{ $ny = $1; }
  elsif ( /^left_map_x.*= ([-.0-9]+)/ )		{ $x_min = $1; }
  elsif ( /^right_map_x.*= ([-.0-9]+)/ )	{ $x_max = $1; }
  elsif ( /^lower_map_y.*= ([-.0-9]+)/ )	{ $y_min = $1; }
  elsif ( /^upper_map_y.*= ([-.0-9]+)/ )	{ $y_max = $1; }
  elsif ( /^elevation_min.*= ([-.0-9]+)/ )	{ $z_min = $1; }
  elsif ( /^elevation_max.*= ([-.0-9]+)/ )	{ $z_max = $1; }
  elsif ( /^grid_size.x.*= ([-.0-9]+)/ )	{ $x_inc = $1; }
  elsif ( /^grid_size.y.*= ([-.0-9]+)/ )	{ $y_inc = $1; }
  elsif ( /^grid_unit.*= (.+)/ )		{ $x_units = $1; $y_units = $1; }
  elsif ( /^elevation_unit.*= (.+)/ )		{ $z_units = $1; }
  elsif ( /^file_title.*= (.+)/ )		{ $title = $1; }
}
close( HFILE );

$node_offset = 1;
$z_scale_factor = 1;
$z_add_offset = 0;
$command = "play lax";
$x_inc = ($x_max - $x_min) / $nx;
$y_inc = ($y_max - $y_min) / $ny;
$remark = "Converted from NGDC TerrainBase CD by Geoffrey Ely";
$GRD_TMPL = "i4 d10 a80 a80 a80 a80 a320 a160";
$header = pack( $GRD_TMPL, $nx, $ny, $node_offset, 0, $x_min, $x_max, 
  $y_min, $y_max, $z_min, $z_max, $x_inc, $y_inc, $z_scale_factor, 
  $z_add_offset, $x_units, $y_units, $z_units, $title, $command, $remark );

open( GFILE, "> $gmt_grd_file" );
print GFILE $header;
close( GFILE );

printf STDERR "reading binary file: %s\n", $binary_file;
printf STDERR "writing gmt grdfile: %s\n", $gmt_grd_file;

system "dd conv=swab < $binary_file >> $gmt_grd_file";
