#!/bin/sh

CDROM=/dev/cdrom

if [ "$#" -eq "1" -o "$#" -eq "2" ]
then
	FILENAME=$1

	if [ "$#" -eq "2" ]
	then
		CDROM=$2
	fi

	CDID=`discid $CDROM`
	if cdrdao read-cd --device $CDROM --driver generic-mmc --datafile $FILENAME.bin $FILENAME.toc
	then
		sed -f INSTALLPATH/tocfix.sed $FILENAME.toc > ${FILENAME}-fixed.toc
		cueconvert ${FILENAME}-fixed.toc $FILENAME.cue
		if nice flac -8 --replay-gain --endian=big --sign=signed --channels=2 --bps=16 --sample-rate=44100 --cuesheet=$FILENAME.cue $FILENAME.bin
		then
			rm -f $FILENAME.bin
			rm -f ${FILENAME}-fixed.toc
			rm -f $FILENAME.toc
			rm -f $FILENAME.cue

			FLACID=`flactag --discid $FILENAME.flac | cut -d':' -f 2| cut -d' ' -f 2`

			if [ "$FLACID" != "$CDID" ]
			then
				echo "**********"
				echo "**********"
				echo "**********"
				echo "********** Disc ID of FLAC doesn't match Disc ID of CD **********"
				echo "**********"
				echo "**********"
				echo "**********"
			fi
		fi
	fi
else
	echo "Usage: $0 cdname [ /path/to/cdrom ]"
fi
