#!/usr/bin/perl

# ccsds_md_resuce.pl

use Time::Local;
use Date::Calc;
use Env qw(EGSE_SW_LIB);
use lib "$EGSE_SW_LIB/perllib/CcsdsLib";

#use lib "/home/matt/perllib/CcsdsLib";

use CcsdsInterface;
use MdInterface;
use MdHeader;

use File::Basename;

do "$EGSE_SW_LIB/pipeline_defs.pl" || die "Can't do pipeline_defs.pl: $!\n";

my %filenames;

$num_args = $#ARGV;
if($num_args == 0) {
    $dirname = $ARGV[0];
}
else {
    if($num_args > 0) {
	while(@ARGV) {
	    $arg = shift;
	    if($arg =~ /^\-/) {
		next;
	    }
	    $dirname = $arg;
	    last;
#	    if($verbose ne "-v") {
#		print STDERR "verbose flag is $verbose\n";
#	    exit;
#	    }
	}
    }
    else {
	print STDERR "Not enough arguments\n"; write_log($filename, "Not enough args"); exit;
    }
}

my @files = `ls $dirname | grep eis_md`;
my @header_list;

###my $archive = MdInterface->new();
my $archive    = CcsdsInterface->new();
my $outArchive = CcsdsInterface->new();

foreach $filen (@files) {
    chomp $filen;
    $last_file = $filen;
    my $file = "$dirname$filen";
    my $short_name = substr $file, -26, 26;
#    my $outfile = $file . ".out";
    my $outfile = "$rescue_dir/$filen";
    my $first = 1;
    my $done = 0;
    my $missing = 0;
    my $md_headers = 0;
    @header_list = ();
    my $i;

    if($archive->openForReading($file)) {
	print STDOUT "\nOpened $file for reading\n";
	if($outArchive->openForWriting($outfile)) {
	    print STDOUT "\nOpened $outfile for writing\n";
	}
	else {
	    print STDOUT "\nCouldn't open $outfile for writing\n";
	}
#	if(open(OUT, "> $outfile")) {
#	    print STDOUT "\nOpened $outfile for writing\n";
#	}
#	else {
#	    print STDOUT "\nCouldn't open $outfile for writing\n";
#	}

	$i = 0;
	while(1) {
	    $missing = 0;
	    $md_data = "";
	    if($archive->nextPacket()) {
		if($archive->isFirstPacketOfSequence()) {
		    $ccsds_hdr_pkt = $archive->getHeaders();
		    $hdr = MdHeader->new();
		    $hdr->populate_header($archive->getPacketData());
		    print STDOUT $hdr->spn(), "\t";
###		    push @header_list, $hdr;
		    $seq_count = $archive->getSequenceCount();
		    $next_seq_count = $seq_count if $first;
		    $first = 0;
		    while($archive->nextPacket()) {
			$next_seq_count = $archive->getSequenceCount();
			if($next_seq_count != (($seq_count + 1) & 0x3FFF)) {
			    if(!(($next_seq_count == 0) and ($seq_count = 0x3FFF))) {
				++$missing;
			    }
			}
			$seq_count = $next_seq_count;
			$ccsds_packet = $archive->getHeaders() . $archive->getPacketData();
			$md_data .= $ccsds_packet;
			last if $archive->isLastPacketOfSequence();
		    }
###		    push @missing_count, $missing;
		    print STDOUT "$missing ";
		    if($missing) {
			write_dummy_packet($outArchive, $hdr);
#			write_dummy_packet($hdr);
		    }
		    else {
			write_packet($outArchive, $ccsds_hdr_pkt, $hdr, $md_data);
#			write_packet($hdr, $md_data);
		    }
		    next;
		}
	    }

	    if($archive->packetIsValid()) {
		# Not found a header packet
		print STDOUT "Missing header\n";
		++$missing;
		while($archive->nextPacket()) {
		    last if $archive->isLastPacketOfSequence();
		}
		last if !($archive->packetIsValid());
	    }
	    else {
		print STDOUT "EOF\n";
		last;
	    }
	}

#	while(@header_list) {
#	    $hdr = shift @header_list;
#	    $cnt = shift @missing_count;
#	    print STDOUT $hdr->spn(), ", $cnt\n";
#	}

    }
    else {
	print STDERR "Unable to open $file\n";
    }

}


sub write_dummy_packet {
    my $archive = shift;
    my $hdr     = shift;

    print STDOUT "write_dummy_packet ", $hdr->spn(), "\n";
}

sub write_packet {
    my $archive = shift;
    my $ccsds   = shift;
    my $hdr     = shift;
    my $data    = shift;

    print STDOUT "write_packet ", $hdr->spn(), "\n";
    $archive->write($ccsds . $hdr->{_data} . $data);
#    syswrite(OUT, $hdr->{_data} . $data, length($hdr->{_data} . $data));
}
