#!/usr/local/bin/perl

#----------------------------------------------------------------------
# ץν
#----------------------------------------------------------------------
$OPT{'fname'} = "MKIND";
undef $OPT{'com'};
$OPT{'stdio'} = 0;
$HELP_MODE = 0;
# ץ
while ($_ = shift @ARGV) {
    /^\s*$/ && next;
    if (s/^-h//)    { $HELP_MODE = 1; next; }
    if (s/^-f//)    { $OPT{'fname'} = shift @ARGV; next; }
    if (s/^-c//)    { $OPT{'com'} = shift @ARGV; next; }
    if (s/^-D//)    { $DEBUG_MODE = 1; next; }
}
if ($OPT{'com'} =~ s/^\|//) {$OPT{'stdio'} = 1;}
# إפν
if ($HELP_MODE) {
    print STDERR "num2nx : Make *.nx and *.npt for IISA\n";
    print STDERR "   usage:  num2nx [options]\n";
    print STDERR " options:\n";
    print STDERR "   -f ... : set input/output",
		 " file name [$OPT{'fname'}(.num/.nx,.npt)]\n";
    print STDERR "   -c ... : set filter [$OPT{'com'}]\n";
    print STDERR "   -help  : show this help\n"; 
    exit(1);
}


open (INPUT, "$OPT{fname}.num") || die "cannot open $OPT{fname}.num\n";

while (<INPUT>) {
    next if /^\#/;
    chomp $_;
    @e = split;
    $LIST[$e[1]] = $e[0];
}
print STDERR "OUTPUT: $OPT{fname}.(nx npt)\n";
$pt = 0; $count = 0;
open (NPT, ">$OPT{fname}.npt");
open (NX, ">$OPT{fname}.nx");

foreach $fname (@LIST) {
    $out = pack "L", $pt;
    print NPT $out;
    print NX $fname;
    if (++$count == 50) {print STDERR "."; $count = 0;}
    $pt += length($fname);

#    print STDERR "$fname\n";

    if (defined $OPT{com} && (-f $fname)) {
	if ($OPT{stdio}) {
	    $str = `cat $fname | $OPT{com}`;
	} else {
	    $str = `$OPT{com} $fname`;
	}
	chomp $str;
	$pt += length($str) + 1;
	print NX "\n$str";
    }
    print NX "\0";
    $pt++;
}
print STDERR "\n";
