#!/bin/bash -e
# Generate hins for input file:
#  MSCGEN=... hint.sh chart-file [chart-type]
[[ "$MSCGEN" ]] || { echo "MSCGEN not defined" >&2; exit 1; }
MSC=$1
SUF=$2
[[ "$SUF" ]] || SUF=${MSC##*.}
lines=(`awk '{t+=length()+1;print t}' $MSC`)
prev=; cur=(1 0); first=(1 0); last=(1 0); pos=1;
emit(){
 [[ -z "$prev" ]] && return
 echo -n "${first[0]}:${first[1]}"
 if [ ${first[0]} -ne ${last[0]} ] || [ ${first[1]} -ne ${last[1]} ]; then
  echo -n '-'
  [ ${first[0]} -ne ${last[0]} ] && echo -n "${last[0]}:"
  echo -n "${last[1]}"
 fi
 echo ":$prev"
}
err=`mktemp msc_err_XXX`
trap "cat $err >&2 && rm $err" EXIT
{ echo; cat $MSC; printf "\0"; for i in `seq $(wc -m $MSC | cut -f1 -d' ')`; do printf "NH$((i-1))\n\0"; done; } |\
  $MSCGEN --tei-mode --nopaths -S $SUF 2>$err |\
  awk 'BEGIN {ORS=" "} { if(7 == split($0, a, "\001")) { for (i=1; i<=length($1); i++) if (substr($1,i,1)=="\0") printf "\n"; else { print substr(a[1], i); break; } } }' |\
  sed '1d' |\
  sed 's/[[:space:]]*$//' |\
  sed '$a\\' |\
  sed 's/\\/\\\\/g' |\
  while read hint; do
    [ "$prev" = "$hint" ] && last=(${cur[*]}) || { emit; prev=$hint; first=(${cur[*]}); last=(${cur[*]}); }
    [[ " ${lines[*]} " =~ " $pos " ]] && ((cur[1]=0, ++cur[0])) || ((++cur[1]))
    ((++pos))
  done
