#!/usr/local/bin/perl -w
################################################################################
#      writer: Dan Tsafrir (dants AT cs DOT huji DOT ac DOT il)
# description: the glue script of the pbs2swf utility.
################################################################################
use warnings;
use strict;
use Data::Dumper;
use Time::Local;
use POSIX;

use lib '.';
use ParseArgv;
use ConversionConfig;
use ConversionLog;
use ParsePBS;
use PrintSWF;


# 1: 
# parse @ARGV leaving in it only non-opts (names of PBS files to be converted). 
# this initialized the %CONFIG (result of parse) to be used in this conversion.
my $tz_str = ParseArgv::parse_argv(\@ARGV, \%CONFIG);

# 2: 
# open both output files: the SWF, and the conversion summary.
my $name     = $CONFIG{other}{output};
$name        =  $1 if( $name =~ m/^(.*)\.swf$/i ); # truncate swf suffix

my $fd_swf;
my $fd_sum;
my $name_swf = "$name.swf";
my $name_sum = "$name.conversion.txt";

open( $fd_swf, "> $name_swf")
    or die "failed opening '$name_swf' for writing: $!\n";
open( $fd_sum, "> $name_sum")
    or die "failed opening '$name_sum' for writing: $!\n";

# 3: 
# switch to time zone of location in which the PBS log was created
$ENV{TZ} = $tz_str;
POSIX::tzset();

# 4: 
# parse the PBS log and convert it to SWF format
#         $swf = ref2arr holding ref2arr-s each representing on job.
#   $anonymize = tables from PBS-value (e.g. some user) to associated SWF-code
# $epoch_start = arrival of first job (@$swf is already normalized).
$| = 1;
printf("%-40s : ", "parsing PBS file(s)");
my ($swf, $anonymize, $epoch_start) = ParsePBS::parse_pbs();	
print "done.\n";

# 5:
# print conversion summary
printf("generating %29s : ", $name_sum);
my $header = PrintSWF::get_swf_header($swf, $anonymize, $epoch_start);
ConversionLog::print_summary($fd_sum, $swf, $anonymize, $header);
print "done.\n";

# 6:
# print the SWF file (along with applying 'overwrite' defaults)
printf("generating %29s : ", $name_swf);
PrintSWF::print_swf_body($fd_swf, $swf, $header);
print "done.\n";


################################################################################
#                                   EOF
################################################################################
