#!/bin/perl -w

# Wrapper to GRIB.pm to decode GRIB.
#
# Copyright (C) 1996, 2002 W. M. Connolley
#
# $Author: wmc $:$Date: 2002/07/26 08:42:33 $:$Revision: 1.3 $
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# http://www.gnu.org/copyleft/gpl.html

use strict;
use GRIB;
use GRID;			# Need this to use "as_grid" method
# use BlockGraph;		# For gaphical output. Will need Tk.pm

my ($Filei, $text, @text, $seg_count);
my $DEBUG = 0;
my $MODE = "BlockGraph";
my $FileOut = "GRIB.grib";

# Setup options
eval "\$$1=\$2" while $ARGV[0] =~ /^(\w+)=(.*)/ && shift;

if ($#ARGV eq -1) {
  print "Usage: GRIB.pl MODE=Text|TextFull|BlockGraph|Grib filenames-list\n";
  exit;
}

#
# Decode GRIB..., looping over files in arg list
#
$seg_count=0;
while ( $Filei=shift @ARGV ) {

open(IN,$Filei);
# If running windows and encountering problems, try uncommmenting the next line (p191).
# binmode IN;
if ($DEBUG) { print "Opening $Filei\n" };

#
# Inner-Main loop; split input file and pass to GRIB.pm in bits
# Note: Splitting on "GRIB" is slightly unsafe - it *could* appear
#       inside a GRIB record - but that is "unlikely"
#
undef $/; $text=<IN>; close(IN);
@text=split(/GRIB/," ".$text); shift @text;

if ($DEBUG) { print "Found ".scalar(@text)." GRIB segements in file of length " . length($text) . "\n" };

for $text (@text) {
  $text = "GRIB".$text;

  if ($DEBUG) { print "  GRIB segement " . $seg_count++ . " found, length ".length($text)."\n" };

  my $grib = GRIB::new(message => \$text, DEBUG=>$DEBUG);
  if ($grib->decode()) { 

    if ($MODE =~ /^Block(Graph)?/i) {
      BlockGraph->draw($grib->{data}, nx => $grib->{nlon}, ny => $grib->{nlat})
    } elsif ($MODE =~ /^Text$/i) {
      print $grib->as_text("data" => "range"),"\n"
    } elsif ($MODE =~ /^TextFull$/i) {
      print $grib->as_text("data" => "full"),"\n"
    } elsif ($MODE =~ /^Grib/i) {
      open OUT,"> $FileOut";
      print OUT $grib->as_grib();
      close OUT
    } elsif ($MODE =~ /^Grid/i) {
      open OUT,"> GRIB.grid";
      print OUT $grib->as_grid();
      close OUT
    } else {
      die "Didn't recognise mode: $MODE"
    };

  } else {

    print $grib->{Error_message},"\n"

  };

};

if ($DEBUG) { print "Finished with $Filei\n" };

};
