#!/bin/perl  -w

# Utility using the GRID package
#
# Copyright (C) 2000 W. M. Connolley
# wmc@bas.ac.uk / http://www.antarctica.ac.uk/met/wmc
#
# $Author: wmc $:$Date: 2002/07/22 20:44:33 $:$Revision: 1.1 $           
#
# 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
#
# Invoke as GRID.pl <options> file.grid
#
# Decodes the messages one-by-one and prints to stdout
#
# Command-line options:
#
# DEBUG=1			# Limited debugging info
# data=full or range		# Default is range
# header=one-line or full	# Default is one-line

use strict;
use GRID;
use GRIB;
use BlockGraph;

# Possible options
my $DEBUG=0;			# or 1
my $data="range";		# or full
my $header="one-line";		# or full
my $MODE = "Text";
my $FileOut = "GRID.out";
my $nmess = -1;

# Setup options
if (!scalar(@ARGV)) {
  print "use: GRIB.pl options file.grid\n";
  exit
} else {
  eval "\$$1=\$2" while $ARGV[0] =~ /^(\w+)=(.*)/ && shift
};

# Read in message file
undef $/; my $text=<>; $text=~s/\r\n/\n/g;

#
# Each GRID message ends with \nNNNN\n so split on that
# (trusting that no message *contains* \nNNNN\n...
#
my $count=0;
for $text (split(/\nNNNN\n/,$text)) {

  if ($text !~ /GRID/) {
    print "no GRID in this fragment... skipping\n";
    next
  };

# Create new grid objct and set message
  my $grid = new GRID; $grid->{DEBUG}=$DEBUG;
  $grid->set_message(\$text);

# Decode and print
  print "Decoding message ",++$count,"\n";
  if ($grid->decode) {

    if ($MODE =~ /^Block(Graph)?/i) {
      $grid->data_2d_to_1d();
      BlockGraph->draw($grid->{data}, nx => $grid->{ngng}, ny => $grid->{nana}, title => $grid->as_text(), height => 200 )
    } elsif ($MODE =~ /^Text/i) {
      print $grid->as_text("data"=>$data, "header"=>$header);
    } elsif ($MODE =~ /^Grib/i) {
      open OUT,"> $FileOut";
      my $grib = $grid->grid2grib();
      print OUT $grib->as_grib();
      close OUT
    } elsif ($MODE =~ /^Grid/i) {
      open OUT,"> $FileOut";
      print OUT $grid->as_grid();
      close OUT
    };

  } else {
    print "Error decoding: ",$grid->{Error_message},"\n";
  };  
# Whether we succeed or fail there may also be warnings
  if ($grid->{Warn}) { print $grid->{Warn_message} };

  last if ($count == $nmess);

};
