#!/bin/perl -w

# Wrapper to CLIMAT.pm to decode CLIMAT.
#
# Author
#   W. M. Connolley 2000 - 2004
#   wmc@bas.ac.uk / http://www.antarctica.ac.uk/met/wmc
#
# 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 CLIMAT;

my ($Filei, $text, @text);
my $DEBUG = 0;
my $ORACLE = 0;			# Output format for Oracle
my $BRIEF =0;			# Output format for quick-checks: subset of ORACLE
my $MMJJJ;

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

if ($#ARGV eq -1) {
  print "Usage: CLIMAT.pl filenames-list\n";
  exit;
}

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

open(IN,$Filei);
if ($DEBUG) { print "Opening $Filei\n" };

#
# Inner-Main loop; split input file and pass to CLIMAT.pm in bits
# Note that we remove CLIMAT TEMP text to avoid confusion on the split.
#
undef $/; $text=<IN>; close(IN);
# Prefixing with " " ensures that the first thing split off is junk. Otherwise
# we have to deal with the special case of CLIMAT being the very first thing.
@text=split(/(CLIMAT \d{5})/," ".$text); shift @text;

while (@text) {

# Irritatingly, we can have
#   CLIMAT MMJJJ
#   IIiii message=
#   IIiii message=
#   ...
#   NNNN

# Get what should be CLIMAT MMJJJ
  $MMJJJ = shift @text;
# Get the rest, and remove trailing junk
  ($text = shift @text) =~ s/\s*NNNN.*//sm;

# Split on the "=" 
  my @text1 = split(/=/,$text);

# Loop over the bits
  for $text (@text1) {

    $text = $MMJJJ . $text;

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

      if ($ORACLE) {
        print $climat->as_oracle . "\n"
      } elsif ($BRIEF) {
        print $climat->as_brief . "\n"
      } else {
        print $climat->as_text . "\n"
      };

    } else {

      print $climat->{Error_message},"\n" unless ($ORACLE)

    };

  };

};

};
