#!/bin/tcsh 

# shell wrapper for chunker

set SCRIPT = `readlink -f "$0"`
set SOURCE = `dirname "$SCRIPT"`  # location where the script is stored
                  # (even if we start via a symbolic link)
set TEMP = /tmp/`date +%s`_$$_

set arguments = ( $* )

# remove syllable boundary symbol '.' from the KAN tier of the BPF
# first, get the --bpf argument for input BPF
set idx = 1
set idxmax = $#
while ( $1 != "--bpf" ) 
  if ( $idx == $idxmax ) break
  shift
  @ idx ++
end
# argument --bpf is missing: pass to chunker for help message
if ( $idx == $idxmax ) then
  $SOURCE/chunker.py $arguments
  exit 1
endif
shift
@ idx ++
set bpf = $1
set bpfidx = $idx
if ( ! -e $bpf ) then 
  echo "ERROR: ${0:t} : cannot find input BPF $bpf - exiting" >> /dev/stderr
  exit 1
endif
##echo arg bpf = $bpf
##echo "arguments[${bpfidx}] = $arguments[${bpfidx}]"
# second, look for argument --outfile
set idx = 1
while ( $arguments[${idx}] != "--outfile" ) 
  if ( $idx == $#arguments ) break
  @ idx ++
end
# argument --outfile is missing: pass to chunker for help message
if ( $idx == $#arguments ) then
  $SOURCE/chunker.py $arguments
  exit 1
endif
@ idx ++
set outfile = $arguments[${idx}]
set outfileidx = $idx
##echo arg outfile = $outfile

# save the original KAN tier
grep '^KAN:' $bpf >! ${TEMP}BPF.KAN
# filter '.' from KAN
awk '/^KAN:/{gsub(/\./,"");print} ! /^KAN:/{print}' $bpf >! ${TEMP}BPF.par
##cat ${TEMP}BPF.par
set arguments[${bpfidx}] = ${TEMP}BPF.par
set arguments[${outfileidx}] = ${TEMP}BPFOUT.par
##echo "arguments = $arguments"

# make the chunking on the filtered BPF and write resulting BPF to ${TEMP}BPFOUT.par
$SOURCE/chunker.py $arguments
set exitCode = $status
if ( $exitCode != 0 ) goto clean

# replace the KAN tier with the original in the result BPF
grep -v '^KAN:' ${TEMP}BPFOUT.par >! "$outfile"
cat ${TEMP}BPF.KAN >> "$outfile"

clean:
rm -rf ${TEMP}*

exit $exitCode

