#!/usr/athena/bin/perl -w
# $HeadURL: file:///afs/sipb.mit.edu/contrib/weather/SVNRep/tools/old-extract-station.pl $
# $Id: old-extract-station.pl 12 2007-09-11 17:17:11Z foley $
# this is a small perl script that will extract all the data from a
# given station id to stdout. It expects to be called as:
# $0 -id XXXX XXX.hourly.txt    or most commonly:
# $0 -id XXXX `find uncompressed/ -name \*hourly.txt`


use strict;
use Getopt::Long;
use IO::File;
use Search::Dict;


# command line values
my $verbose = 0;   # option variable with default value (false)
my $stationid = '';
GetOptions (
	        'verbose|v+' => \$verbose,
	        'stationid|station|id|sid=i', => \$stationid,
	    );

die "Must specify a station id" unless($stationid);
die "That doesn't look like a good station id" unless(length $stationid == 5);
die "Must specify some input files" unless(scalar @ARGV > 0);


foreach my $file (@ARGV) {

    print STDERR "pulling station information for $stationid from $file\n";



    my $FILEH = new IO::File "$file", "r";
    unless(defined $FILEH) {
	print STDERR "couldn't open file $file\n";
	next;
    }
    
    # we need to skip the first line, cause it's header
    my $header = $FILEH->getline || die "I shouldn't die killing the first line.";


    look $FILEH, "$stationid" || die "urk";

    print_lines($stationid, $FILEH);


}

sub print_lines {
    # we expect a prepositioned file handle as well.
    my $id = shift;
    my $FILEH = shift;


    while(<$FILEH>) {

	# we have to be sneaky and skip a line if we're at on the first.
	next if($_ =~ /^Wban/);
	next if($_ =~ /^\s*$/);
	
	$_ =~ /([0-9]+)\,*/;
	
	if($1 == $id) {
	    print $_;
	}
	else {
	    return;
	}
    }
}
