#!/opt/perl/bin/perl

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

my %par=get_defaults();
my $baseurl = 'ftp://cddis.gsfc.nasa.gov/pub/gps/products/ionex';
my $ionex_dir = $par{IONEX_DIR};
my $cal = get_date(shift,'cal');

my ($yyyy,$doy) = split (' ',get_date($cal,'doy'));
my $yy = unpack('x2a2',$yyyy);

# Create the directory if it doesn't already exist
my $directory = "$ionex_dir/$yyyy";
if ( ! -d $directory ) { mkpath $directory; }
# Filename
my $file = "jplg${doy}0.${yy}i";
#my $file = "igsg${doy}0.${yy}i";

if ( ! -e "$directory/$file" &&
     ! -e "$directory/${file}.Z" ) {
    print "Changing to $directory\n";
    chdir $directory;
    my $url = "$baseurl/$yyyy/$doy/${file}.Z";
    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);
    } 
    `gunzip -f "${file}.Z"`;
} else {
	print "Already have IONEX file $file\n";
}


0;
