#!/bin/csh

# extracts a tier from a BPF file and writes it into a TextGrid (praat)

# usage par2TextGrid type=MAU file1.par [file2.par ...]

# implemented for bpftype = 4, type = MAU,

# general remarks:
# this script assumes that the labels are in ascending timely order; that 
# means that the last segment is also the last in the signal file

set SOURCE = /homes/schiel/bin

if ( ! -d $SOURCE || ! -e $SOURCE/Muster.TextGrid || ! -e $SOURCE/bpf-four2TextGrid.awk ) then 
  echo "First set the variabel SOURCE to your location to run this script"
  echo "In this location you must store par2TextGrid, Muster.TextGrid and"
  echo "bpf-*2TextGrid.awk"
  exit 3
endif 

set type = MAU


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

if ( $1 == "" ) then 
  echo "usage: par2TextGrid type=BPF-type file1.par [file2.par ...]"
  exit 1
endif

set bpf = $1
set TextGrid = ${bpf:r}.TextGrid

switch ( $type )
case MAU:
	set bpftype = 4
	breaksw
default:
	echo "Unknown BPF type $type"
	exit 2
	breaksw
endsw
#echo type = $type
#echo bpftype = $bpftype

set SAMPLERATE = `grep '^SAM:' $bpf | gawk '{print $2}'`

switch ( $bpftype )
case 1:
	echo "BPF type 1 not implemeted yet"
	exit 2
	breaksw
case 2:
	echo "BPF type 1 not implemeted yet"
	exit 2
	breaksw
case 3:
	echo "BPF type 1 not implemeted yet"
	exit 2
	breaksw
case 4:
	set MAXTIME = `grep "^${type}:" $bpf | tail -n 1 | gawk '{print $2}'`	
	@ MAXTIME += `grep "^${type}:" $bpf | tail -n 1 | gawk '{print $3}'`
	@ MAXTIME ++
	set MAXTIME = `echo $MAXTIME | gawk '{ maxtime = $1 / '"${SAMPLERATE}"'.0; printf("%f", maxtime)}'`
	set NUMSEG = `grep "^${type}:" $bpf | wc -l`
	cat $SOURCE/Muster.TextGrid | sed "s/##XMAX/$MAXTIME/" |sed "s/##NUMSEG/$NUMSEG/" >! $TextGrid
	grep "^${type}:" $bpf | gawk -v SAMPLERATE=$SAMPLERATE -f $SOURCE/bpf-four2TextGrid.awk >> $TextGrid
	breaksw
case 5:
	echo "BPF type 1 not implemeted yet"
	exit 2
	breaksw
endsw	
