#!/bin/csh

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

# usage merge-tiers destpartiturfile sourcepartiturfile

# destpartiturfile contains the existing Bas Partitur file with or without
# the tiers contained in sourcepartiturfile. If dest partiturfile already 
# contains a 
# tier of the same type as in sourcepartiturfile, it is deleted from 
# destpartiturfile without warning and
# the new tier from ourcepartiturfiles is added to destpartiturfile. 
# sourcepartiturfile must
# contain a header.  To add single tiers without header use 
# the script merge-tier.
# The resulting destpartiturfile is checked for consistency in word links 
# using chkpartitur.csh. This can cause trouble if a 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-tiers [check=yes] destpartiturfile sourcepartiturfile'
  echo '       merges all tiers contained in source to destination'
  echo '       and checks result with chkpartitur.csh.'
  echo '       existing tiers in destination will be overwritten.'
  echo '       source and destination must be valid BPF files;'
  echo '       to insert a single tier use the tool mergetier'
  exit 1
endif
set pf = $1 
set tf = $2

# get types to be inserted
set typelist = `cat $tf | gawk -f $SOURCE/merge-tiers.awk`
# deleted old tiers
foreach type ( $typelist )
  cat $pf | grep -v "^${type}" >! /tmp/merge-tier$$.tmp
  /bin/rm -f $pf 
  cat /tmp/merge-tier$$.tmp >! $pf
end
rm -f /tmp/merge-tier$$.tmp
# insert new tiers
foreach type ( $typelist )
  grep "^${type}" $tf >> $pf
end
# check results
if ( $check == "yes" ) $SOURCE/chkpartitur.csh $pf

exit 0
