#!/usr/bin/perl -w
use File::Copy;
use Time::Local;

# This script captures data from an IASI daily data files and writes
# the data to ODS files


# Determine the date of the data to process
my $day_of_data = 20180901;


# =============================================================================
# Copy the file to the temporary directory
my $from_file = "/data/data215/nprovs/data/orbital_archive/nucaps_test_npp/nucaps_test_npp_" . $day_of_data . ".iddf.gz";
my $to_file   = "/data/data065/nprovs/data/matchup/DailyFiles_incoming/storms/nucaps_test_npp_" . $day_of_data . ".iddf.gz";

printf("Copying the file: %s\n", $from_file);
copy($from_file, $to_file);

printf("Gunzipping the file\n");
system "gunzip " . $to_file;

my $input_file = "/data/data065/nprovs/data/matchup/DailyFiles_incoming/storms/nucaps_test_npp_" . $day_of_data . ".iddf";


# =============================================================================
# Create a temporary directory into which the pieces of the file 
# will be written

my $source_dir = "/data/data065/nprovs/source/graphics/ods_capture/nucaps/version2";
my $work_dir = "/data/data065/nprovs/data/matchup/DailyFiles_incoming/storms";
my $xml_dir = "/data/data065/nprovs/scripts/graphics/storms";
my $ods_dir = "/data/data065/nprovs/data/ods";

$file_name = "nucaps_test_npp_" . $day_of_data . ".ods";
$ods_file = $ods_dir . "/" . $file_name;


chdir $work_dir;
mkdir $work_dir . "/ods";


# =============================================================================
# Create the ODS file for

symlink $input_file, "in.file" or warn "Cannot link to in.file";
symlink $work_dir . "/ods", "out.dir" or warn "Cannot link to out.dir";
symlink $source_dir . "/nucaps_test.xml", "parm.file" or warn "Cannot link to parm.file";
symlink $source_dir . "/parm_defs", "parmdefs.dir" or warn "Cannot link to parmdefs.dir";

system $source_dir . "/createODSFromNUCAPS.x \"NUCAPS Test SNPP\" " . $day_of_data;

unlink "in.file" or warn "Cannot unlink in.file";
unlink "out.dir" or warn "Cannot unlink out.dir";
unlink "parm.file" or warn "Cannot unlink parm.file";
unlink "parmdefs.dir" or warn "Cannot unlink parmdefs.dir";


# Copy the filter_options.xml file to the ods directory
system "cp " . $source_dir . "/filtering_options.xml ods/filtering_options.xml";


# =============================================================================
# Zip everything and then delete the temporary directory and everything in it
system "zip -r " . $ods_file . " ods";

printf("\nRemoving the ODS directory\n");
system "rm -r " . $work_dir . "/ods";


# Remove the temporary file
unlink $input_file;

# end of file
