#!/usr/bin/env perl

# ./select_md_file.pl ~/data/mission/2024/09/packet_check/ccsds_hdrs.20240903.txt eis_md_20240905_1119593091

my $nargs = $#ARGV;
#print "Number of args = $nargs\n";

die "Need a ccsds hdr dump text file as input & a pattern" unless $nargs eq 1;

my $file = $ARGV[0];
my $pattern = $ARGV[1];

die "Can't find file: $!" unless ( -e $file );

while(<>) {
    last if m/$pattern/
}

print "\n"; # Give filter_ccsds_hdrs.pl a blank line to start otherwise it fails
print "$_";

while(<>) {
    print "$_";
    last if(/packets missing/);
}

exit 0;


while(<>) {
    last if /^$/;
}

while(<>) {
    if(/eis_md/) {
	print $_;
	$count = -1;
	next;
    }

    next if /Time/;
#       next if /ccsds/;
    if(/ccsds/) {
###	@data = split;
	if($count == -1) {
###	    print "T $data[0]\n";
	    print "\n";
	    next;
	}
	print "+ $count\n\n";
###	print "T $data[0]\n";
	$count = 0;
	next;
    }

    next if /Number/;

    chomp;

    if(/^$/) {
	next;
    }

#    if(/Number of gaps/) {
#	@data = split;
#	print "G $data[3]\n";
#    }
#    if(/Number of packets/) {
#	@data = split;
#	print "M $data[4]\n\n";
#    }

#    if(/^$/) {
#               print "+ $count\n\n";
#               $count = 0;
#	next;
#    }

    if(/Missing/) {
	if(/16128/ or /16198/) {
	    print STDOUT "Artifact gap\n";
	    next;
	}
#               next if /16128/;
	@data = split;
	print "+ $count\n" unless $count< 0;
	print "- ", $data[3], "\n";
	$count = 0;
	next;
    }

    @data = split /,/;
    if($data[5] == 1) {
	print "+ $count\n" unless $count < 1;
	print "h $data[0], $data[6], $data[7]\n";
	$count = 0;
	next;
    }

    if($data[5] == 2) {
	print "+ $count\n" unless $count < 1;
	print "e $data[0]. $data[6], $data[7]\n";
	$count = -1;
	next;
    }
#       if($data[0] eq '***') {
#               print "+ ", $count, "\n";
#               print "- ", $data[3], "\n";
#               $count = 0;
#               next;
#       }
    ++$count;
}
