#!/bin/bash
#
# Transpose a book for Horn in F.

if [ $# != 1 ]; then
    echo "Usage: makeFHorn.sh <book dir name>"
    exit 1
fi

# Transpose down (return 0) if top note was > e (> a for horn).
transposedown()
{
    (($2 > 109))
}

dir=`pwd`

booke=$dir/$1
outdir=$dir/$1-HornInF

mkdir -p $outdir/Compact

# Copy book component items.
cp $booke/*.txt $outdir

echo "Horn in F" > $outdir/instrument.txt

find $booke -name "*.abc" | sort |
    while read filename
    do
        name=`basename $filename .abc`

        dir=`dirname $filename`
        basedir=`basename $dir`
        compact=""
        if [ "$basedir" = "Compact" ]; then
            compact="Compact/"
        fi

        range=`./abcrange.py $filename`

        # Transpose concert pitch up a fifth.
        # If there are any notes above 'd' (Horn 'g'), transpose
        # down a seventh instead.
        transpose=5
        if transposedown $range; then
            transpose=-7
        fi

        # There's no point in having transposed chords. Remove from the
        # abc before transposing. Some badly formed chord items can give
        # erroneous output from abc2abc (like, strings of binary gibberish).
        sed -e "s/\"[^\"]*\"//g" $filename > $outdir/$name.abc.tmp

        # Transpose. By default abc2abc will report errors in the output,
        # but this messes up output formatting so stop it. Also force all
        # output to be in treble clef; some lower tunes with the odd high
        # note will otherwise appear in bass clef, which is not what this
        # crap horn player wants.
        abc2abc $outdir/$name.abc.tmp -e -t $transpose | \
            sed -e "/^ *K:/s/$/ clef=treble/" > $outdir/$compact$name.abc
        rm $outdir/$name.abc.tmp
    done
