#!/usr/bin/perl
use Text::Template;

$summaryTemplate = Text::Template->new(SOURCE => '/home/ssurul01/workspace/EVS-Java-Service/templates/XMLSummaryResults.tmpl')
               or die "Couldn't construct template: $Text::Template::ERROR";
$overviewTemplate = Text::Template->new(SOURCE => '/home/ssurul01/workspace/EVS-Java-Service/templates/XMLOverviewResults.tmpl')
               or die "Couldn't construct template: $Text::Template::ERROR";

$dcmFileName = $ARGV[0];
$path = $ARGV[1];
$guid = $ARGV[2];

#print $path."\n".$dcmDirName."\n".$guid."n";

validateDCMFile($dcmFileName, $path, $guid);

sub  validateDCMFile {
  my ( $dcmFileName, $path, $guid) = @_;
  my $errorCount = 0;
  my $warningCount = 0;
  my $evalString = "";

  $errorFile = $path. "/dciodvfy.out";
  $evalString = "/opt/dicom3tools_1.00.snapshot.20070621/bin/1.2.6.20.i686/dciodvfy 1> $errorFile 2>&1";
  #$evalString = "/tmp/dciodvfy $dcmFileName 1> $errorFile 2>&1";
  `$evalString`;

  open(TEMP,$errorFile)|| die "Error opening dciodvfy.out: $!\n";
  while(<TEMP>){
    chomp;
    #print "DCIODVFY: $_\n";
    $testResult .= $_."\n";
    $errorCount++ if(/^Error/);
    $warningCount++ if(/^Warning/);
  }
  close TEMP;
  $testStatus ='PASSED' if ($errorCount == 0);
  $testStatus ='FAILED' if ($errorCount > 0);
  #$testResult = $testStatus;

@timestruct = (localtime(time()));
$testTime = sprintf("%02d%02d%02d", $timestruct[2],$timestruct[1],$timestruct[0]);

($day, $month, $year) = (localtime)[3,4,5];
#printf("The current date is %04d %02d %02d\n", $year+1900, $month+1, $day);
$testDate = sprintf("%04d%02d%02d", $year+1900, $month+1, $day);

%vars =
  (
   testDate => $testDate,
   testTime =>$testTime,
   errorCount => $errorCount,
   warningCount => $warningCount,
   testStatus => $testStatus,
   testResult => $testResult,
   objGUID => $guid,
 );

open(XML,">$path/overview-results.xml")|| die "Error opening overview-results.xml: $!\n";
$overviewResult = $overviewTemplate->fill_in(HASH => \%vars, OUTPUT => \*XML);
#$result = $template->fill_in(HASH => \%vars, OUTPUT => \*STDOUT);

open(XML,">$path/summary-results.xml")|| die "Error opening summary-results.xml: $!\n";
$summaryResult = $summaryTemplate->fill_in(HASH => \%vars, OUTPUT => \*XML);

#if (defined $result) { print $result }
#else { die "Couldn't fill in template: $Text::Template::ERROR" }

#  print "Error: $errorCount\n" if ($errorCount);
#  print "Warning: $warningCount\n" if ($warningCount);
#  print "Status: FAILED\n" if ($errorCount > 0);
#  print "Status: SUCCESS\n" if ($errorCount == 0);
}
