#!/bin/tcsh

# wrapper for subtitle.py
# that corrects TRO entries that contain only a punctuation

set SCRIPT = `readlink -f "$0"`
set SOURCE = `dirname "$SCRIPT"`  # location where the script is stored 
                           # (even if we start via a symbolic link)
setenv LANG en_US.UTF-8  # defines the behavior of text processing, sorting etc.

$SOURCE/subtitle.py $*
set err_code = $status
if ( $err_code != 0 ) then
  exit $err_code
endif
if ( "$*" == "--version" ) exit 0

set OUT = `echo "$*" | sed 's/^.*--outfile \([^ ]*\).*$/\1/'`
if ( "$OUT" == "" ) then
  echo "ERROR: ${0:t} : cannot determine OUT from command line: $*"
  exit 1
endif 
if ( ! -e "$OUT" ) then
  echo "ERROR: ${0:t} : cannot find output from subtitle.py $OUT"
  exit 1
endif 
set OUTFORMAT = `echo "$*" | sed 's/^.*--outformat \([^ ]*\).*$/\1/'`
if ( "$OUTFORMAT" == "bpf" || "$OUTFORMAT" == "bpf+trn" ) then
  set PID = $$_`date "+%s"`
  egrep -q '^TRO: -1 [!:.?…]' "$OUT"
  if ( $status == 0 ) then
    awk '! /^TRO:/{ print } /^TRO:/{if(oldline!=""){if($2=="-1"){print oldline $3; oldline=""}else{print oldline; oldline=$0}}else{oldline=$0}}END{print oldline}' "$OUT" >! /tmp/${PID}_TRO.par
    cp /tmp/${PID}_TRO.par "$OUT"
  endif
  rm -f /tmp/${PID}*
endif

exit 0

