#!/bin/perl

#
# Use: station.pl options files
# Or:  gunzip -c files.gz | station.pl options
#
#  where:
#    options is a set of 0 or more assignments
#      sensible ones are:
#        stat=wmocode - eg 89009
#        y=year - eg 80, 81, etc.
#        m=month - 01, 02, etc
#        d=day - you get the idea
#        h=hour - 00 or 12 in general
#        clev=level - level to write out, implemented as a string grep.
#        nlev=level - level to write, implemented numerically.
#    files is a list of files to search
#

# Examples:
#   station.pl 82.06.txt			  - Simplest case. Extract all data from 82.06.txt
#   station.pl 82.*.txt				  - Same as above, but for all the months in '82
#   station.pl stat=89009 h=12 8?.*		  - Only get 89009 at 12Z
#   gunzip -c list-of-files | station.pl nlev=500 - Get 500 hPa level
#

#
# Author: W. M. Connolley
# This-version: Sept 1997
# Requires: perl interpreter; works with v5.03; lower versions probably OK.
# Use: This program may be freely used, copied and modified *only* for academic purposes
# Warranty: This program comes with *no warranty*; all responsibility is disclaimed
#

# Set defaults for station, year, etc. These may be reset by next bit of code
$stat="89...";
$y="..";
$m="..";
$d="..";
$h="..";
$nlev=0;
$clev=".";

# Set command-line switches 
eval "\$$1=\$2" while $ARGV[0] =~ /^(\w+)=(.*)/ && shift;

# Read piped data or from listed files
while (<>) {

# Get Station and date from first line
$STAT=substr($_,0,5);
$Y=substr($_,5,2);
$M=substr($_,7,2);
$D=substr($_,9,2);
$H=substr($_,11,2);

# Get N lines line
$NLINES=<> % 10000;

# Get Other info line...
$_=<>;

# Get sfcP line
chop($SFCP=<>);

if ($STAT =~ /$stat/ && $Y =~ /$y/ && $M =~ /$m/ && $D =~ /$d/ && $h =~ /$h/) { $OUT="$STAT $Y $M $D $H $SFCP\n" };
# Loop to read in the lines
for ($i=0; $i<$NLINES; $i++) {
  $FOUND=0;
  $LINE=<>;
  ($P, $H, $T, $TD, $D, $D, $C)=split(' ',$LINE);
  if ($P =~ /$clev/ && (!$nlev || $P == $nlev) && $STAT =~ /$stat/) { $OUT.=$LINE; $FOUND++ };
  if ($FOUND) { print $OUT };
}

}
