#!/bin/sh

# Shellscript mit " chmod u+x dateiname " freigeben!

# Function: Compares corresponding entries in marfile and nist-headers of 
#           all Signalfiles belonging to this marfile

# Usage: VM_nist_mar_check signalfile
#        Marfile and signalfile are in the same directory. 


sigfile=$1
if test -r $sigfile
 then :
 else
  echo "Error:" $sigfile "not a readable file!"
  exit 1
fi
signame=`echo $sigfile | sed 's#.*\/\([0-9a-z\.]*\)$#\1#'`
if test "$sigfile" = "$signame"
 then
  sigpath=""
 else
  sigpath=`echo $sigfile | sed 's#\(.*\/\)[0-9a-z\.]*$#\1#'`
fi

marfile=`echo $sigfile | sed 's/[hncrmpdw][1-9]\.[a1][l6]$/\.mar/'`
if test -r $marfile
 then :
 else
  echo "Error:" $marfile "not a readable file!"
  exit 1
fi

marname=`echo $marfile | sed 's#.*\/\([0-9a-z\.]*\)$#\1#'`
echo -n $marname $signame":  "

language=`echo $marname | sed 's/[0-9][0-9][0-9][ab][crt].mar//'`

spk=`head -n 19 $sigfile | grep "speaker_id" | awk '{printf("%s", $3)}'`
marstart=`echo $signame | sed 's/\.[a1][l6]$//'`
argument=$marstart"_[0-9][0-9][0-9]_"$spk
turns=`egrep -e $argument $marfile`
if test "$turns" = ""
 then 
  echo
  echo "Error: Marfile and signalfile do not correspond!" 
 else
  marsta=`echo $marstart | sed 's/..$//'`
  if test $language = "m"
   then
    argument="[ 0-9]*"$marsta".\([0-9]\)_[0-9][0-9][0-9]_[A-Z][A-Z][A-Z]_[EGJ][NEA][GRP]"
   else
    argument="[ 0-9]*"$marsta".\([0-9]\)_[0-9][0-9][0-9]_[A-Z][A-Z][A-Z]"
  fi
  chananz=`egrep -e $marsta $marfile | sed "s/\$argument/\1/" | sort | uniq | tail -2c`
  chananz=`expr $chananz + 0`
  if test $chananz -lt 2
   then 
    echo
    echo "Error in marfile! " 
   else
    mars=`echo $marstart | sed 's/..$//'`
    sigext=`echo $sigfile | sed 's/.*\(\.[a1][l6]\)$/\1/'`
    if test $language = "m"
     then
      argument="[ 0-9]*\("$mars".[0-9]\)_[0-9][0-9][0-9]_[A-Z][A-Z][A-Z]_[EGJ][NEA][GRP]"
     else
      argument="[ 0-9]*\("$mars".[0-9]\)_[0-9][0-9][0-9]_[A-Z][A-Z][A-Z]"
    fi
    files=`cat $marfile | sed "s/\$argument/\1\$sigext/" | sort | uniq`
    channo=1 
    countturns=0
    while test $channo -le $chananz
     do
      file=`echo $files | cut -d " " -f $channo`
      if test -r $sigpath$file
       then 
        spk=`head -n 19 $sigpath$file | grep "speaker_id" | awk '{printf("%s", $3)}'`
        marstart=`echo $file | sed 's/\.[a1][l6]$//'`
        argument=$marstart"_[0-9][0-9][0-9]_"$spk
        turns=`egrep -e $argument $marfile | wc -l`
        echo -n $file $spk $turns " "
        countturns=`expr $countturns + $turns`
       else
        echo
        echo "Error:" $sigpath$file "not a readable file!"
      fi
      channo=`expr $channo + 1`
     done
    echo
    nrofturns=`cat $marfile | wc -l`
    if test $countturns -ne $nrofturns
     then
      echo "Error in marfile!"
    fi
  fi
fi
