#! /bin/bash

set -o errexit

cd "${0%/*}"

rm -rf c-code *.c *.h readme.txt
unzip 26204-600_ANSI-C_source_code.zip

for FILE in c-code/*.c  c-code/*.h c-code/readme.txt ; do
    tr -d '\r' <$FILE >${FILE#*/}.new
    mv ${FILE#*/}.new ${FILE#*/}
done
echo >>typedef.h

rm -r c-code

patch <amrwb-intsizes.patch
patch <amrwb-any-cflags.patch

for FILE in {dec,enc}_if.{c,h} ; do
    echo "modifying file $FILE"
    if test $FILE = ${FILE%.h} ; then
	ENDSTRING="^}"
    else
	ENDSTRING=");"
    fi
    sed -n "/^[^# ][^ ]* ._IF_..code/,/$ENDSTRING/p" <$FILE >$FILE.def
    sed 's/^\([^# ][^ ]*\) \(._IF_..code\)/\1 GP3\2/
	 s:ifndef IF2:if 1 /* & */:
	 s:ifdef IF2:if 0 /* & */:
	' <$FILE.def >$FILE.all
    sed 's/^\([^# ][^ ]*\) \(._IF_..code\)/\1 IF2\2/
	 s:ifndef IF2:if 0 /* & */:
	 s:ifdef IF2:if 1 /* & */:
	' <$FILE.def >>$FILE.all
    sed "/^[^# ][^ ]* ._IF_..code/,/$ENDSTRING/c/* Double the code with different defines and names */" <$FILE |
    sed "/Double the code with different defines and names/r$FILE.all" >$FILE.new
    mv $FILE.new $FILE
    rm $FILE.def $FILE.all
done
