#!/bin/csh

# this script is a general purpose tool to replace single tiers
# in given Bas Partitur files

# usage merge-tier [check=no] partiturfile tierfile

# partiturfile contains the existing Bas Partitur file with or without
# the tier stored in tierfile. If partiturfile already contains a 
# tier of the same type, it is deleted from the file without warning and
# the new tier from tierfile is added to the partiturfile. tierfile must not 
# contain a header. Only the first tier is handled,  
# if tierfile contains more than one
# tier. The final partiturfile is checked for consistency in word links (check=yes)
# using chkpartitur.csh. This can cause trouble if the new tier is still unknown
# to that script.

set SOURCE = /homes/schiel/bas/partitur
set check = yes

# Actually do the argument parsing here

while ( "$1" != "" )
	switch ("$1")
	case *=*:
		set key = `echo $1 | cut -d= -f1`
		set val = `echo $1 | cut -d= -f2`
		eval "set $key "= \'"$val"\'
		unset key val
		shift
		breaksw
        default:
		break
        endsw
end

# end option parser

if ( $#argv != 2 ) then
  echo 'usage: merge-tier [check=no] partiturfile tierfile'
  exit 1
endif
set pf = $1 
set tf = $2

set type = `cat $tf | grep '^[A-Z0-9][A-Z0-9][A-Z0-9]:' | head -n1 | sed 's/^\([A-Z0-9][A-Z0-9][A-Z0-9]\):.*$/\1/'`
echo $type
cat $tf | grep "^${type}:" >! /tmp/merge-tier-tf$$.tmp
cat $pf | grep -v "^${type}:" >! /tmp/merge-tier$$.tmp
/bin/rm $pf 
cat /tmp/merge-tier$$.tmp /tmp/merge-tier-tf$$.tmp > $pf
rm -f /tmp/merge-tier$$.tmp /tmp/merge-tier-tf$$.tmp
if ( $check == "yes" ) $SOURCE/chkpartitur.csh $pf

exit 0
