#!/usr/bin/env perl

# this program takes the pmSourceIO_CMF.in.c template file and generates the .c version based on the given I/O format made

if (@ARGV != 3) { die "USAGE: mksource (template) (cmfmode) (output)\n"; }

$template = $ARGV[0];
$cmfmode = $ARGV[1];
$output = $ARGV[2];

if (! -f $template) { die "missing template file $template\n"; }

# validate the cmfmode

# see if we can add in PS1_DV* and PS1_SV* as well...
%cmfmodes = ("PS1_V1", 1,
	     "PS1_V2", 2,
	     "PS1_V3", 3,
	     "PS1_V4", 4);

print "1: $cmfmodes{1}\n";
print "PS1_V1: $cmfmodes{'PS1_V1'}\n";

open (FILE, "$template") || die "failed to open template $template\n";
@list = <FILE>;
close (FILE);

open (FILE, ">$output");

# operations we can perform:
# @CMFMODE@ : replace with $cmfmode
# @ALL@ : remove and keep the rest of the line
# @=MODE@ : remove and keep if cmfmode == MODE
# @>MODE@ : remove and keep if cmfmode > MODE
# @<MODE@ : remove and keep if cmfmode > MODE

foreach $line (@list) {

    # replace @CMFMODE@ wherever it appears
    $line =~ s|\@CMFMODE\@|$cmfmode|g;
    
    if ($line =~ m|\@ALL\@|) {
	$line =~ s|\@ALL\@\s*||;
    }

    ($isMode) = ($line =~ m|\@=(\S*)\@|);
    ($gtMode) = ($line =~ m|\@>(\S*)\@|);
    ($ltMode) = ($line =~ m|\@<(\S*)\@|);
    
    if ($isMode) {
	if ($isMode ne $cmfmode) { next; }
	$line =~ s|\@=\S*\@\s*||;
    }

    if ($gtMode) {
	# print "gtMode : $line\n";
	$thisLevel = $cmfmodes{$gtMode};
	$myLevel = $cmfmodes{$cmfmode};
	print "gtMode : $gtMode vs $cmfmode, $thisLevel, $myLevel\n";
	if ($myLevel <= $thisLevel) { next; }
	$line =~ s|\@>\S*\@\s*||;
    }

    if ($ltMode) {
	# print "ltMode : $line\n";
	$thisLevel = $cmfmodes{$ltMode};
	$myLevel = $cmfmodes{$cmfmode};
	print "ltMode : $ltMode vs $cmfmode, $thisLevel, $myLevel\n";
	if ($myLevel >= $thisLevel) { next; }
	$line =~ s|\@<\S*\@\s*||;
    }

    print FILE $line;
}

close (FILE);

exit 0;
