#!/bin/bash

#########################################
#					#
## Programs needed			#
#  mac, bchunk, lame			#
#					#
## Use					#
#  ape2mp3 <NAME.ape> <NAME.cue>	#
#					#
## Written				#
#  by solidether			#
#					#
## Contact				#
#  solidether@gmx.net			#
#					#
## GPL					#
#  this litle pice of software is	#
#  under GPL.				#
#  check: www.gnu.org			#	
#					#
#########################################

case "$1" in
	"--help")	echo "use: ape2mp3 <NAME>.ape <NAME>.cue"
			exit 0
			;;
	"-h")		echo "use: ape2mp3 <NAME>.ape <NAME>.cue"
			exit 0
			;;
esac

if(test -x `whereis -b mac|sed -e 's/[^*]*\:\ //'|sed -e 's/\ [^*]*//'`)
then 	echo "mac: found"
else 	echo "mac: not found"
	echo "check: http://sourceforge.net/projects/mac-port/"
	exit 1
fi

if(test -x `whereis -b bchunk|sed -e 's/[^*]*\:\ //'|sed -e 's/\ [^*]*//'`)
then    echo "bchunk: found"
else    echo "bchunk: not found"
	echo "check: http://he.fi/bchunk/"
        exit 1
fi

if(test -x `whereis -b lame|sed -e 's/[^*]*\:\ //'|sed -e 's/\ [^*]*//'`)
then    echo "lame: found"
else    echo "lame: not found"
	echo "check: http://lame.sourceforge.net/"
        exit 1
fi

typ=`file "$1"`
case "$typ" in
	"$1: data")	echo ""$1" ok"
			;;
	*)		echo "Error: use: ape2mp3 <NAME>.ape <NAME>.cue"
			exit 0
			;;
esac

typ=`file "$2"`
case "$typ" in
	"$2: ASCII text, with CRLF line terminators")	echo ""$2" ok"
			;;
	*)		echo "Error: use: ape2mp3 <NAME>.ape <NAME>.cue"
			exit 0
			;;
esac


mac "$1" Image.wav -d

if(test -f Image.wav)
then
	rm "$1"
else
	echo "Error: no Wav-Image"
        exit 0
fi

bchunk -w Image.wav "$2" track
	
if(test -f track01.wav)
then
        rm Image.wav
	rm "$2"
else
	echo "Error: no Tracks"
        exit 0
fi

for i in `ls | grep track`
do
	lame --preset extreme $i `echo "$i"|sed -e 's/\.wav/\.mp3/'`
	rm $i
done
