#!/opt/perl/bin/perl

use strict;
use GPS::DATES;
use GPS::Defaults;
use File::Path;

my %par=get_defaults();
#my $baseurl = 'http://mars.hg.tuwien.ac.at/~ecmwf1/GRID';
my $baseurl = 'http://ggosatm.hg.tuwien.ac.at/DELAY/GRID/STD';
my $vmf1dir = $par{VMF1GRID_DIR};
my $cal = get_date(shift,'cal');

my ($yyyy,$doy) = split (' ',get_date($cal,'doy'));
my $yy = unpack('x2a2',$yyyy);
my @components = ('ah','aw','zh','zw');

foreach my $component (@components) {
    # Create the directory if it doesn't already exist
    my $directory = "$vmf1dir/$yyyy/$component";
    if ( ! -d $directory ) { mkpath $directory; }

    foreach my $hh ( qw(00 06 12 18) ) {
        if ( ! -e "$directory/$component$yy$doy.h$hh" && 
             ! -e "$directory/$component$yy$doy.h$hh.gz" ) {
            print "Changing to $directory\n";
            chdir $directory;
            my $url = "$baseurl/$yyyy/$component$yy$doy.h$hh";
            print "Getting $url\n";
            `wget -Nq $url`;
            if (($? >> 8) != 0) {
                my $exit_code = ($? >> 8);
                print "wget failed with exit code $exit_code\n";
                exit($exit_code);
            } 
            `gzip -f $component$yy$doy.h$hh` if -e "$component$yy$doy.h$hh";
        } else {
                print "Already have VMF1 file $component$yy$doy.h$hh\n";
        }
    }

}

0;
