#!/bin/sh
#    RipEnc 1.1--Frontend to rip, encode, and name mp3's
#    Copyright (C) 1999, 2000, 2001 by Michael J. Parmeley <mjparme@asde.net    > 

#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software Foundation,
#    Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.

#Trap some signals and run the forcequit() function when those signals occur...assures that RipEnc cleans
#up after itself if <Ctrl-C> or such is used to abort RipEnc
trap 'forcequit' INT
trap 'forcequit' KILL
trap 'forcequit' TERM

#Function called by main3() to search the PATH (via which) for supplied argument...cuts
#down on redundant code...thanks Keenan Brock
searchFor()
{
     for search in $*
     do
          which ${search} 1>& /dev/null
          check=`echo $?`

          if [ ${check} -eq 1 ]
          then
               echo ${search} "not found"
          else
               echo ${search} "found...`which ${search}`"
          fi
     done

     return
}

#Fill the option variables with some default values...if there is a ripencrc file in your .ripenc directory
#those values will override these. Really only helpful the first time the script is ran
setDefaults()
{
     RCDIR=${HOME}/.ripenc
     TEMPDIR=${RCDIR}
     SAVETO=${HOME}
     TEMPSAVETO=${SAVETO}
     ENCODER=bladeenc
     RIPPER=tosha
     METHOD=manual
     XMCDLIB=/var/X11R6/lib/xmcd
     NCONVENT=artist-name_of_song.mp3
     select=1
     WHOLE=no
     DEVICE=/dev/cdrom
     SMALL=no
     ID3TOOL=mp3info
     BITRATE=128
     RCREAD=0
     EJECT=no

     #Needed for CDDB access with "wget"
     SERVER=freedb.freedb.org
     DOMAIN=my.host.com
     CGI=/~cddb/cddb.cgi
}

#Function that is ran if the above signals are trapped
forcequit ()
{
     if [ "${ABORT}" = "1" ] ;
     then
          echo ; echo "I am assuming you just want to quit the viewing of the log.  If you want to quit RipEnc press CtrlC again"
          ABORT=0
          return
     fi

     echo
     echo Aborting Ripenc...
     cleantemp

     if [ "${RCREAD}"=="1" ] ;
     then
          saverc
     fi

     exit 1
}

#Function cleans up temp files in the .ripenc directory...runs when RipEnc is quit and is run by forcequit()
cleantemp ()
{
    checkrm ${TEMPDIR}/ripname.txt
    checkrm ${TEMPDIR}/cdnames.txt
    checkrm ${TEMPDIR}/toc1
    checkrm ${TEMPDIR}/toc2
    checkrm ${TEMPDIR}/tracks.txt
    checkrm ${TEMPDIR}/tmprip
    checkrm ${TEMPDIR}/tracks.new
    checkrm ${TEMPDIR}/cddb.query
    checkrm ${TEMPDIR}/cddb.query.temp
    checkrm ${TEMPDIR}/cddb.mult
    checkrm ${TEMPDIR}/cddb.mult.temp

    return
}

#Called by cleantemp()...checks each file for existance before trying to remove it
#Makes adding files that may need to be removed easier so that you don't need
#an if statement for each file you add
checkrm ()
{
     if [ -f $1 ] ;
     then
          rm $1
     fi
}       

#Called when RipEnc exits to write the options to the ripencrc file so they can be used next time RipEnc is run
saverc ()
{
    echo SAVETO="'"${SAVETO}"'" > ${RCDIR}/ripencrc
    echo ENCODER="'"${ENCODER}"'" >> ${RCDIR}/ripencrc
    echo RIPPER="'"${RIPPER}"'" >> ${RCDIR}/ripencrc
    echo METHOD="'"${METHOD}"'" >> ${RCDIR}/ripencrc
    echo XMCDLIB="'"${XMCDLIB}"'" >> ${RCDIR}/ripencrc
    echo NCONVENT="'"${NCONVENT}"'" >> ${RCDIR}/ripencrc
    echo select="'"${select}"'" >> ${RCDIR}/ripencrc
    echo WHOLE="'"${WHOLE}"'" >> ${RCDIR}/ripencrc
    echo DEVICE="'"${DEVICE}"'" >> ${RCDIR}/ripencrc
    echo SMALL="'"${SMALL}"'" >> ${RCDIR}/ripencrc
    echo ID3TOOL="'"${ID3TOOL}"'" >> ${RCDIR}/ripencrc
    echo BITRATE="'"${BITRATE}"'" >> ${RCDIR}/ripencrc
    echo EJECT="'"${EJECT}"'" >> ${RCDIR}/ripencrc

    #Needed for CDDB access with "wget"
    echo SERVER="'"${SERVER}"'" >> ${RCDIR}/ripencrc
    echo DOMAIN="'"${DOMAIN}"'" >> ${RCDIR}/ripencrc
    echo CGI="'"${CGI}"'" >> ${RCDIR}/ripencrc

    if [ "${EJECT}" = "yes" ]
    then
         echo foundEjectTool="'"${foundEjectTool}"'" >> ${RCDIR}/ripencrc
    fi
}

#Tests to see if the selected working directory exits...if not asks the user if they want to create it
#if no value is entered the old value is restored
testsaveto ()
{
    if [ ! "${SAVETO}" = "" ] && [ ! -d ${SAVETO} ] ;
    then
        echo -n ${SAVETO} "does not exist, create [y/n]? "
        read create

        if [ "${create}" = "y" ] ;
        then
            mkdir -p ${SAVETO}
        else
            SAVETO=${OLDSAVETO}
        fi
    fi

    if [ "${SAVETO}" = "" ] ;
    then
        SAVETO=${OLDSAVETO}
    fi
}

#This moves temp files from previous versions of RipEnc to the newer location...only used once and only if an earlier
#version of RipEnc was used (prior to version 0.6 I believe...check changelog)
checkoldrc ()
{
    # Make the .ripenc directory to store all the files used by ripenc
    mkdir -p ${RCDIR}
    if [ -f ${HOME}/.ripencrc ] || [ -f ${HOME}/.ripencsed ] ;
    then
        mv ${HOME}/.ripencrc ${RCDIR}/ripencrc &> /dev/nul
        mv ${HOME}/.ripencsed ${RCDIR}/ripencsed &> /dev/null
    fi
}

#This creates the sed source file if it doesn't already exists...probably only used first time RipEnc is ran...also
#if the ripencsed is mistakenly erased
checkforsed ()
{
    if [ ! -f ${RCDIR}/ripencsed ] ;
    then
        echo "/^$/d" > ${RCDIR}/ripencsed
        echo "s/ /_/g" >> ${RCDIR}/ripencsed
        echo "s/'//g" >> ${RCDIR}/ripencsed
        echo "s/*//g" >> ${RCDIR}/ripencsed
        echo "s/,//g" >> ${RCDIR}/ripencsed
        echo "s/)//g" >> ${RCDIR}/ripencsed
        echo "s/(//g" >> ${RCDIR}/ripencsed
        echo "s/\.//g" >> ${RCDIR}/ripencsed
    fi
}

#Retrieves the CDDB information, extracts needed information and formats it
cda_cddb ()
{
    #Set up the enviroment variable for cda
    export XMCD_LIBDIR=${XMCDLIB}

    #cda is a command line utility that comes with XMCD
    #Turn on the CD device specified in preferences
    cda -dev ${DEVICE} on
    echo ; echo -n "Getting CDDB information for CD with CDA..."

    #Get the table of contents for the current CD and write to toc1
    cda -dev ${DEVICE} toc > ${TEMPDIR}/toc1

    echo "done"

    #Turn off cda device
    cda -dev ${DEVICE} off

    #Could grab the genre from the cda output right here so it can be put
    #into the id3 tag...do it later

    #Remove the Total Time and Disc ID lines from the table of contents...also remove blank lines and some misc characters
    #write file to toc2
    sed -e '/Accessing CDDB/d' -e '/Genre:/d' -e '/Total Time/d' -e '/Disc ID/d' -e '/^$/d' -e 's/\.//g' -e 's/\[//g' -e 's/\]//g' ${TEMPDIR}/toc1 > ${TEMPDIR}/toc2

    parseCDDB
}

wget_cddb ()
{
     #Run "discid" to get the Disc ID and track offsets
     QUERYINFO=`discid ${DEVICE}`

     #Give the user some feedback
     echo ; echo -n "Getting CDDB information for CD with WGET..."

     #wget's -O option didn't like ${TEMPDIR}/toc1 so I stuck it in a variable and it took it...probably has
     #something to do with quoting...this works though so who cares
     QUERY=${TEMPDIR}/cddb.query
     TOC1=${TEMPDIR}/toc1

     #Query the server using wget to get category and check for multiple matches
     wget --quiet -O ${QUERY} "http://${SERVER}/${CGI}?cmd=cddb+query+${QUERYINFO}&hello=${USER}+${DOMAIN}+RipEnc+${VERSION}&proto=5"

     serverResponse=`sed -ne '1p' ${TEMPDIR}/cddb.query | cut -d" " -f1`

     #Check for multiple matches
     if [ ${serverResponse} -eq 210 ]
     then
          echo ; echo ; echo "Multiple matches found...please select one of the following choices:"

          #Need to keep cddb.query intact so we will utilize another temp file
          #Removes the first line of cddb.query which just tells us that there are multiple matches
          sed -e '1d' ${TEMPDIR}/cddb.query > ${TEMPDIR}/cddb.mult

          #Deal with the carriage returns
          sed -e 's/.$//g' ${TEMPDIR}/cddb.mult > ${TEMPDIR}/cddb.mult.temp
          mv ${TEMPDIR}/cddb.mult.temp ${TEMPDIR}/cddb.mult

          #Get the top line of cddb.mult to put in a menu of choices for user
          #Do this until the last line is reached which is a terminating "." in the cddb.mult file
          nextLine=`sed -ne '1p' ${TEMPDIR}/cddb.mult`
          count=1

          while [  "${nextLine}" != "." ]
          do
               echo "${count}) ${nextLine}"
               count=`expr ${count} + 1`

               #Delete the top line of the cddb.mult file
               sed -e '1d' ${TEMPDIR}/cddb.mult > ${TEMPDIR}/cddb.mult.temp
               mv ${TEMPDIR}/cddb.mult.temp ${TEMPDIR}/cddb.mult

               #Get the new top line
               nextLine=`sed -ne '1p' ${TEMPDIR}/cddb.mult`
          done

          echo -n "? " ; read choice

          #Add one to the choice because we will be retriving the actual line from the cddb.query
          #file which was left intact so still has the top server response line that was deleted
          #from cddb.mult therefore the users choice will be one line behind
          line=`expr ${choice} + 1`

          #Print the line of the chosen match in cddb.query.temp
          sed -ne ''${line}'p' ${TEMPDIR}/cddb.query > ${TEMPDIR}/cddb.query.temp

          #Pad the front of the line in cddb.query.temp with another field (seperated by a space)
          #so that the CATEGORY and DISCID fields are 2 and 3 as needed for the two statements
          #immediately following the if-then...write it back to cddb.query.
          #we know have a file like we would if we did not have multiple matches and we can continue normally
          sed -e 's/^/200 /' ${TEMPDIR}/cddb.query.temp > ${TEMPDIR}/cddb.query
     fi

     CATEGORY=`sed -ne '1p' ${TEMPDIR}/cddb.query | cut -d" " -f2`
     DISCID=`sed -ne '1p' ${TEMPDIR}/cddb.query | cut -d" " -f3`

     #Read the CDDB info for the CD
     wget --quiet -O ${TOC1} "http://${SERVER}/${CGI}?cmd=cddb+read+${CATEGORY}+${DISCID}&hello=${USER}+${DOMAIN}+RipEnc+${VERSION}&proto=5"

     #This sed command gets rid of those damn Carriage Returns that are at the end of each line in the retrieved
     #file...these little fuckers pissed me off until I figured out what was going on and how to get rid of them!
     #Not sure how safe this is but it will do for now...
     sed -e 's/.$//g' ${TEMPDIR}/toc1 > ${TEMPDIR}/toc1.temp
     mv ${TEMPDIR}/toc1.temp ${TEMPDIR}/toc1

     #This line parses the retrieved query into the same format as cda_cddb() does...this enables us to now
     #call parseCDDB for both cda and wget since both are now in the same format
     sed -ne '/^DTITLE/p' -ne '/^TTITLE/p' -e '/^$/d' -e 's/\.//g' -e 's/\[//g' -e 's/\]//g' ${TEMPDIR}/toc1 | cut -d"=" -f2- > ${TEMPDIR}/toc2

     parseCDDB
}

parseCDDB ()
{
    #Top line of toc2 now has the Artist name and Album name seperated by a "/"
    #Extract Artist name from toc2 and store in CHECKVARIOUS
    CHECKVARIOUS=`sed -ne '1p' ${TEMPDIR}/toc2 | cut -d "/" -f1 | tr A-Z a-z | sed -e 's/ //g'`

    #various artist CD's have a few different ways of being identified in the CDDB...check CHECKVARIOUS variable
    #for the three known ones
    if [ "${CHECKVARIOUS}" = "variousartists" -o "${CHECKVARIOUS}" = "[soundtrack]" -o "${CHECKVARIOUS}" = "various" ] ;
    then
         #No need to set ARTIST since it is contained in the song name for various artist CD's
         ALBUM=`sed -ne '1p' ${TEMPDIR}/toc2 | cut -d "/" -f2-`
         #Extract song names from toc2 throwing out all other information, take out some characters that are in some but not
         #all listings and write information to cdnames.txt

         #if we are using wget there is no track number nor track time in front of the song title; therefore we do
         #not need the "cut" command in the first pipe...the rest needs to stay the same
         if [ "${METHOD}" = "wget" ]
         then
              sed -e '1d' ${TEMPDIR}/toc2 | sed -e 's/\//-/g' -e 's/ - /-/g' -e 's/ -- /-/g' -f ${RCDIR}/ripencsed > ${TEMPDIR}/cdnames.txt
         else
              sed -e '1d' ${TEMPDIR}/toc2 | cut -d" " -f5- | sed -e 's/\//-/g' -e 's/ - /-/g' -e 's/ -- /-/g' -f ${RCDIR}/ripencsed > ${TEMPDIR}/cdnames.txt
         fi

         #Remove the two toc files (toc1 and toc2)
         rm ${TEMPDIR}/toc[1-2]
    else
         #Must also extract ARTIST name from file for regular CD's
         ARTIST=`sed -ne '1p' ${TEMPDIR}/toc2 | cut -d "/" -f1`
         ALBUM=`sed -ne '1p' ${TEMPDIR}/toc2 | cut -d"/" -f2-`

         #if we are using wget there is no track number nor track time in front of the song title; therefore we do
         #not need the "cut" command in the first pipe...the rest needs to stay the same
         if [ "${METHOD}" = "wget" ]
         then
              sed -e '1d' ${TEMPDIR}/toc2 | sed -e 's/\///g' -f ${RCDIR}/ripencsed > ${TEMPDIR}/cdnames.txt
         else
              sed -e '1d' ${TEMPDIR}/toc2 | cut -d" " -f5- | sed -e 's/\///g' -f ${RCDIR}/ripencsed > ${TEMPDIR}/cdnames.txt
         fi

         rm ${TEMPDIR}/toc[1-2]
    fi

    #If the user wants to rip whole CD all the songs names are written into the ripname.txt file which
    #contains the song names that will be ripped...if not then user is sent to the song selection
    #menu to choose the songs to be ripped
    if [ "${WHOLE}" = "yes" ] ;
    then
         #This line puts track numbers in ripname.txt since they were taken out before...read sed man
         #page to see how it works
         sed -e '=' ${TEMPDIR}/cdnames.txt | sed -e 'N' -e 's/\n/ /g' >> ${TEMPDIR}/ripname.txt
         rip
    else
         choosecddb
    fi 
}

#Used if user doesn't want to use CDDB 
manual ()
{
    echo -n "What is the name of the Artist? "
    read ARTIST 
    echo -n "What is the name of the Album? "
    read ALBUM
    snum=0
    while [ "${snum}" != "" ] ;
    do
        echo
        echo -n "What song number do you wish to rip (hit enter to end selecting songs)? "
        read snum

        if [ "${snum}" = "" ] ;
        then
             continue
        fi

        echo -n "What is the name of song #"${snum}"? "
        read sname
        sname=`echo ${sname} | sed -f ${RCDIR}/ripencsed`

        #Song names that are to be ripped end up in ripname.txt no matter which method is used
        echo ${snum} ${sname} >> ${TEMPDIR}/ripname.txt
    done

    #Call the confirm() function so user can verify song names to be ripped...not necessary when using
    #CDDB naming
    confirm
}

#This is the function that calls toggle and showmenu...also this function also writes the song names with plus signs in
#front of them to the ripname.txt file which are the songs that will actually be ripped and encoded
choosecddb ()
{
    showmenu
    while test "${choice}" != ""
    do
        toggle ${choice}
        showmenu
    done

    #If nothing is entered at the prompt in showmenu() then the above while loop exits and any
    #song name with a "+" in front of it is written to ripname.txt...this line also puts track
    #numbers in front of the file names...read sed man page to see how it works
    sed -e '=' ${TEMPDIR}/tracks.txt | sed -e 'N' -e 's/\n/ /g' | sed -ne 's/+//p' > ${TEMPDIR}/ripname.txt
    rip
}

#This function puts the songs in the appropriate list...either in the tracklist or list of songs that will be
#ripped and encoded...all has to do if there is a plus sign in front of the song name...the toggle() functions
#either removes or adds the plus sign in front of the appropriate song name
showmenu ()
{
    clear
    n=0

    #Writes cdnames.txt to tracks.txt....tracks.txt is a temporary file used in the song selection process
    if [ ! -f ${TEMPDIR}/tracks.txt ]
    then
         cp ${TEMPDIR}/cdnames.txt ${TEMPDIR}/tracks.txt
    fi

    #If the song name in tracks.txt has a "+" in front of it then they are printed in the Songs to Rip/Encode list
    #If it doesn't then it is printed in the Tracklist list (songs that won't be encoded)
    echo ; echo -e "\033[1mTracklist\033[0m"
    echo "-----------------------"
    sed -e '=' ${TEMPDIR}/tracks.txt | sed -e 'N' -e 's/\n/ /g' | awk '$2 !~ /+/ { print "  "$1"  " $2}'
    echo ; echo -e "\033[1mSongs to Rip/Encode\033[0m"
    echo "-------------------"
    sed -e '=' ${TEMPDIR}/tracks.txt | sed -e 'N' -e 's/\n/ /g' | awk '$2 ~ /+/ { print "  "$1"     "$3 }'
    echo 
    echo "Enter a track number to toggle whether or not to rip it, or <enter> to continue"
    echo -n "? "
    read choice
}

#Adds or removes a plus sign in front of the selected song name...if there is one there it is taken out if there isn't one
#there it is added...hence the name toggle()
toggle ()
{
     #the song number that is input at the prompt in showmenu gets a plus
     #sign in front of it...if there already was one in front of it now there are two seperated by a space
     #and since it was already selected it now needs to be de-selected...it is written to tracks.new
     sed -e ''$1's/^/+ /' ${TEMPDIR}/tracks.txt > ${TEMPDIR}/tracks.new

     #...so if the selected song has two pluses in front of it (in tracks.new) both pluses need to be removed and
     #the song will be put back in the Tracklist by showmenu() since it no longer has any plus signs
     #in front of it...this info is then written back to tracks.txt...easiest way to understand it is to
     #trace it through!
     sed -e ''$1's/^+ +//' ${TEMPDIR}/tracks.new > ${TEMPDIR}/tracks.txt

     #tracks.new is removed...
     rm -f ${TEMPDIR}/tracks.new
}

#Only used if manual naming was used...decided not to confirm with the CDDB naming option because it is pretty interactive
#with the toggle capabilities...seemed redundant
confirm()
{
    echo ; echo "These are the files you have chosen to be ripped"
    echo ; cat ${TEMPDIR}/ripname.txt ; echo

    echo -n "Does this look right to you [y/n]? "
    read uhoh

    if [ "${uhoh}" = "n" ] ;
    then
         rm ${TEMPDIR}/ripname.txt
         manual
    else
         rip
    fi
}

#Function performs the actual ripping process and takes care of naming the files according to the selected naming
#options
rip()
{
    echo
    SAVETEMP=${SAVETO}
        
    if [ "${ID3TOOL}" != "none" ] ;
    then
         echo -n "What is the publishing year? " ; read YEAR
    fi

    #Run the sed source file (ripencsed) on the ARTIST and ALBUM to prepare it for naming...mostly used to get the
    #spaces out of the name and replace them with "_"
    ARTIST=`echo ${ARTIST} | sed -f ${RCDIR}/ripencsed`
    ALBUM=`echo ${ALBUM} | sed -f ${RCDIR}/ripencsed`

    #Read the num and title out of ripname.txt ripping each song until ripname.txt is empty
    cat ${TEMPDIR}/ripname.txt | while read num title
    do
        ARTIST=`echo ${ARTIST} | sed -f ${TEMPDIR}/ripencsed`
        formatnum=`printf '%02d' ${num}`

        #Have to test for a various artist Cd again...then NAME is set according to selected naming convention
        #The reason we need to have seperate sections for various artist and regular Cd's is because
        #on various Cd's the artist is contained in the $title so the artist doesn't have to be
        #seperately added to the NAME variable like for regular Cd's...this is a product of how various artist
        #cd's are stored in the CDDB
        if [ "${CHECKVARIOUS}" = "variousartists" -o "${CHECKVARIOUS}" = "[soundtrack]" -o "${CHECKVARIOUS}" = "various" ] ;
        then
            if [ "${select}" = "1" ] ;
            then
                 NAME=`echo ${title} | tr A-Z a-z`
            fi
            if [ "${select}" = "2" ] ;
            then
                 NAME=`echo ${formatnum}-${title} | tr A-Z a-z`
            fi
            if [ "${select}" = "3" ] ;
            then
                 NAME=${title}
            fi
            if [ "${select}" = "4" ] ;
            then
                 NAME=${formatnum}-${title}
            fi
            ARTIST="VARIOUS_ARTIST_CD"
        else
            if [ "${select}" = "1" ] ;
            then
                 NAME=`echo ${ARTIST}-${title} | tr A-Z a-z`
            fi
            if [ "${select}" = "2" ] ;
            then
                 NAME=`echo ${formatnum}-${ARTIST}-${title} | tr A-Z a-z`
            fi
            if [ "${select}" = "3" ] ;
            then
                 NAME=${ARTIST}-${title}
            fi
            if [ "${select}" = "4" ] ;
            then
                 NAME=${formatnum}-${ARTIST}-${title}
            fi
            if [ "${select}" = "5" ] ;
            then
                NAME=${formatnum}-${title}
                CREATE=`echo ${ARTIST}--${ALBUM} | sed -e 's/ //g' -e 's/\///g'`
                mkdir -p ${SAVETO}/${CREATE}
                SAVETO=`echo ${SAVETO}/${ARTIST}--${ALBUM} | sed -e 's/ //g'`
            fi
            if [ "${select}" = "6" ] ;
            then
                NAME=${formatnum}-${title}
                ARTIST=`echo ${ARTIST} | sed -e 's/ //g' -e 's/\///g'`
                ALBUM=`echo ${ALBUM} | sed -e 's/ //g' -e 's/\///g'`
                mkdir -p ${SAVETO}/${ARTIST}/${ALBUM}
                SAVETO=`echo ${SAVETO}/${ARTIST}/${ALBUM} | sed -e 's/ //g'`
            fi
            if [ "${select}" = "7" ] ;
            then
                 NAME=${ARTIST}-${ALBUM}-${formatnum}-${title}
            fi
        fi

        echo
        echo -n "Now ripping the song " ; echo -n ${title} ; echo -n " by " ; echo -n ${ARTIST} ; echo -n " from the album " ; echo ${ALBUM}
        echo

        #Check the RIPPER variable to see which ripper to start
        case ${RIPPER} in
             cdparanoia)
                  cdparanoia -d ${DEVICE} -w ${num} ${SAVETO}/${NAME}.wav
                  ;;
             cdda2wav)
                  cdda2wav -D ${DEVICE} -t ${num} ${SAVETO}/${NAME}.wav
                  rm ${SAVETO}/*.cddb
                  rm ${SAVETO}/*.inf
                  ;;
             tosha)
                  tosha -q -f wav -d ${DEVICE} -t ${num} -o ${SAVETO}/${NAME}.wav
                  ;;
             dagrab)
                  dagrab -d $DEVICE -f $SAVETO/$NAME.wav $num
                  ;;
             none)
                  echo "Not Ripping"
        esac

        #Put the just ripped name into the encode queue
        echo ${SAVETO}/${NAME}.wav >> ${TEMPDIR}/encode

        #This line is the line that finally fixed the multiple CD id3 tag problem...thanks Devon Jones! (plus another few lines in encodeit()
        #Write needed info for the id3 tags into encode.id3
        echo ${num} ${title} ${ARTIST} ${ALBUM} ${YEAR} >> ${TEMPDIR}/encode.id3

        if [ "${ENCODER}" != "none" ] && [ "${SMALL}" = "yes" ] ;
        then
             #If the small hard drive option is set each song is encoded after it is ripped
             encodeit
        fi

        SAVETO=${SAVETEMP}

        if [ "${ENCODER}" != "none" ] && [ "${SMALL}" != "yes" ] && [ ! -f ${TEMPDIR}/lock.encode ] ;
        then
             #If the small hard drive option is not set then encodeit() is called and started
             #in the background and will work until the encode queue is empty...will encode any
             #current songs in the queue and any added later
            encodeit &

            #Write the PID of the above encodeit() call to lock.encode...lets RipEnc know that there is an
            #encoding process running...the PID seems like a good thing to write to the file instead of using
            #and empty file
            echo $! > ${TEMPDIR}/lock.encode
        fi
    done


     #This will eject the CD after ripping depending on the status of the EJECT variable...will use either
     #"eject" or "cda" depending on the first one found in option11()...looks for eject first then cda
     if [ "${EJECT}" = "yes" ]
     then
          if [ "${foundEjectTool}" = "eject" ]
          then
               echo "Ejecting CD with eject"
               eject ${DEVICE}
          fi

          if [ "${foundEjectTool}" = "cda" ]
          then
               echo  "Ejecting CD with cda"
               cda -dev ${DEVICE} on
               cda disc eject
               cda -dev ${DEVICE} off
          fi
     fi

     SAVETO=${SAVETEMP}
}

#Performs the encoding...this function either runs in the background or if the small hard drive option is used
#it runs after each song is ripped
encodeit ()
{
     #This allows us to enter the while loop the first time!
     e=0

     #${e} is the name of the song read from the encode queue...when the file is empty ${e} will
     #be = to nothing and we will exit out of the while loop
     while [ "${e}" != "" ]  ;
     do
          e=`sed -ne '1p' ${TEMPDIR}/encode`
          case ${ENCODER} in
            bladeenc)
                bladeenc -DELETE -QUIT -${BITRATE} ${e} 1>& ${TEMPDIR}/encode.log
                ;;
            8hz-mp3)
                #8hz-mp3, l3enc, lame, and xingmp3enc do not automatically rename the .wav file as a .mp3 file so
                #RipEnc needs to do it
                ENEW=`echo ${e} | sed -e 's/\.wav$/.mp3/g'`
                8hz-mp3 -b ${BITRATE} ${e} ${ENEW} 1>& ${TEMPDIR}/encode.log
                rm ${e}
                ;;
            l3enc)
                ENEW=`echo ${e} | sed -e 's/\.wav$/.mp3/g'`
                l3enc -br ${BITRATE} ${e} ${ENEW} 1>& ${TEMPDIR}/encode.log
                rm ${e}
                ;;
            lame)
                ENEW=`echo ${e} | sed -e 's/\.wav$/.mp3/g'`
                lame -h -b ${BITRATE} ${e} ${ENEW} 1>& ${TEMPDIR}/encode.log
                rm ${e}
                ;;
            xingmp3enc)
                ENEW=`echo ${e} | sed -e 's/\.wav$/.mp3/g'`
                xingmp3enc -Q -B ${BITRATE} ${e} ${ENEW} 1>& ${TEMPDIR}/encode.log
                rm ${e}
                ;;
            mp3enc)
                 ENEW=`echo ${e} | sed -e 's/\.wav$/.mp3/g'`
                 mp3enc -br ${BITRATE} -if ${e} -of ${ENEW} 1>& ${TEMPDIR}/encode.log
                 rm ${e}
                 ;;
            oggenc)
                 #The ogg format has its own tagging system which can be put in at encode
                 #time...so we need to do it here instead of waiting until after the song
                 #is encoded
                 i=`sed -ne '1p' ${TEMPDIR}/encode.id3`
                 id3title=`echo ${i} | cut -d" " -f2`
                 ID3ARTIST=`echo ${i} | cut -d" " -f3`
                 ID3ALBUM=`echo ${i} | cut -d" " -f4`

                 #oggenc changes the name of the file by itself...removes .mp3 and adds .ogg
                 #(can be overridden by -o)

                 #This oggenc line should tag the ogg file just like a id3 tag does for a mp3
                 #However it doesn't do it correctly...it does encode the song and put the tag
                 #in it with a title but it won't put the ARTIST in...it actually tries to read
                 #the variable after the "-a" switch as a song name to encode...not sure
                 #if there is something wrong with my command line or there is a bug in oggenc
                 #oggenc ${e} -b ${BITRATE} -a "${id3ARTIST}" -t "${id3title}" -l "${ID3ALBUM}"  1>& ${TEMPDIR}/encode.log

                 #We will just keep it simple until I can figure out the above problem
                 oggenc ${e} -b ${BITRATE} 1>& ${TEMPDIR}/encode.log
                 rm -f ${e}
                 ;;
            gogo)
                 :
                 ;;
            none)
                echo "Not Encoding"
                ;;
          esac

          #Remove the just encoded song from the encode queue
          sed -e '1d' ${TEMPDIR}/encode >> ${TEMPDIR}/encodetemp
          mv ${TEMPDIR}/encodetemp ${TEMPDIR}/encode

          #Read the id3 tag info from the encode.id3 file
          i=`sed -ne '1p' ${TEMPDIR}/encode.id3`
          if [ "${ID3TOOL}" != "none" ] ;
          then
               #The next five lines are the final fix to the multiple CD id3 tag problem...the appropriate values
               #are read from the encode.id3 file and passed to the id3 taggers
               id3num=`echo ${i} | cut -d" " -f1`
               id3title=`echo ${i} | cut -d" " -f2`
               ID3ARTIST=`echo ${i} | cut -d" " -f3`
               ID3ALBUM=`echo ${i} | cut -d" " -f4`
               ID3YEAR=`echo ${i} | cut -d" " -f5`

               #Replaces .wav in the filename to .mp3 so we are tagging the filename with .mp3 instead of .wav which
               #no longer exists
               ENEW=`echo ${e} | sed -e 's/\.wav$/.mp3/g'`
               case ${ID3TOOL} in
                    mp3info)
                         mp3info -t "${id3title}" -a "${ID3ARTIST}" -l "${ID3ALBUM}" -c "Track ${id3num}" -y "${ID3YEAR}" ${ENEW} > /dev/null
                         ;;
                    id3ren)
                         id3ren -nocfg -tagonly -song "${id3title}" -album "${ID3ALBUM}" -artist "${ID3ARTIST}" -year "${ID3YEAR}" -comment "Track ${id3num}" -nogenre ${ENEW}
                         ;;
               esac
          fi

          #Remove the id3 info for the song that was just tagged
          sed -e '1d' ${TEMPDIR}/encode.id3 > ${TEMPDIR}/encode.id3.new
          mv ${TEMPDIR}/encode.id3.new ${TEMPDIR}/encode.id3

          #Get the next song name from the encode queue
          e=`sed -ne '1p' ${TEMPDIR}/encode`
     done

    SAVETO=${SAVETEMP}

    #Remove the lock.encode after the encode process is done
    rm -f ${TEMPDIR}/lock.encode
}

#Lets you know if a encoding process is running in the background and will show the size of the encode.log
#file if it exists
status()
{
     clear
     echo "RipEnc version ${VERSION}, Copyright (C) 1999, 2000, 2001  Michael J. Parmeley"
     echo "<mjparme@asde.net>, RipEnc comes with ABSOLUTELY NO WARRANTY"
     echo

     #This section lets you view the status of any background encoding process
     if [ -f ${TEMPDIR}/lock.encode ] ;
     then
          echo "There is currently an encoding process running in the background"
     else
          echo "There is currently NO encoding process running in the background"
     fi

     if [ -f ${TEMPDIR}/encode.log ] ;
     then
          #Gets the file size of the encode.log from a long directory listing (ls -lag)
          SIZE=`ls -lag ${TEMPDIR}/encode.log | awk '{ print $5 }'`
          echo "Your encode.log file is "${SIZE}" bytes long."
     else
          echo "There is no encode.log file."
     fi

     echo
     return
}

#Presents the main menu choices and calls the appropriate functions
mainMenu()
{
     while [ "${mainMenu}" != "6" ]
     do
          #Call status() to show current status of RipEnc
          status
          echo -e "< Enter 'd' for details, 'v' to view the encode log, or 'del' to delete the encode log>"
          echo
          echo -e "1) Change Preferences"
          echo -e "2) Start Ripping/Encoding"
          echo -e "3) Check PATH for supported software"
          echo -e "4) List the files in your working directory"
          echo -e "5) About"
          echo -e "6) Exit"
          echo -n "? " ; read mainMenu

          #Change d, v, or del to uppercase...harmless to numbers
          mainMenu=`echo ${mainMenu} | tr a-z A-Z`

          #Thanks to Keenan Brock who made this section a lot shorter!
          case ${mainMenu} in
               1|2|3|4|5|6|D|V|DEL)
                    main${mainMenu}
                    ;;
          esac

done
 }

#Presents the option menu and calls the appropriate function
preferMenu()
{
     while [ "${optionMenu}" != "13" ]
     do
          status
          echo -e "1) Change working directory........................[\033[1m"${SAVETO}"\033[0m]"
          echo -e "2) Choose encoder..................................[\033[1m"${ENCODER}"\033[0m]"
          echo -e "3) Choose ripper...................................[\033[1m"${RIPPER}"\033[0m]"
          echo -e "4) Choose id3 tool.................................[\033[1m"${ID3TOOL}"\033[0m]"
          echo -e "5) Choose manual naming or tool for CDDB access....[\033[1m"${METHOD}"\033[0m]"

          if [ "${METHOD}" = "wget" ]
          then
               echo
               echo -e "     5a) Please enter CDDB server name.............[\033[1m"${SERVER}"\033[0m]"
               echo -e "     5b) Please enter CDDB server's CGI directory..[\033[1m"${CGI}"\033[0m]"
               echo -e "     5c) Please enter your domain name.............[\033[1m"${DOMAIN}"\033[0m]"
               echo
          fi

          echo -e "6) Setup XMCD_LIBDIR variable for CDA..............[\033[1m"${XMCDLIB}"\033[0m]"
          echo -e "7) Set preferred naming convention.................[\033[1m"${NCONVENT}"\033[0m]"
          echo -e "8) Rip whole CD?...................................[\033[1m"${WHOLE}"\033[0m]"
          echo -e "9) Set small hard drive option?....................[\033[1m"${SMALL}"\033[0m]"
          echo -e "10) Please select your Cd-Rom device...............[\033[1m"${DEVICE}"\033[0m]"
          echo -e "11) Eject CD after ripping is complete?............[\033[1m"${EJECT}"\033[0m] ${foundEjectTool}"
          echo -e "12) Set the Bitrate for the encoded MP3's..........[\033[1m"${BITRATE}"\033[0m]"
          echo -e "13) Return to Main Menu"
          echo -n "? " ; read optionMenu

          #Thanks goes to Keenan Brock here too
          case ${optionMenu} in
               1| 2| 3| 4| 5| 6| 7| 8| 9| 10| 11| 12)
                    option${optionMenu}
                    ;;
               13)
                    #Return to mainmenu()...need to reset optionMenu to something other than 13
                    #or we won't be able to get back into the preferences menu
                    optionMenu=0
                    return
                    ;;
               5a| 5b| 5c)
                    if [ "${METHOD}" = "wget" ]
                    then
                         option${optionMenu}
                    fi
                    ;;
          esac

     done
 }

#Gets info about the encoding process...gets the info from a "ps auxww" and by counting the lines in the encode
#queue...also displays name of songs that still need to be encoded
mainD()
{
     if [ ! -f ${TEMPDIR}/lock.encode ] ;
     then
          echo ; echo "There doesn't appear to be a encoding process running!"
          echo ; echo "Please press enter to continue" ; read continue
     else
          echo ; echo "Encoder      PID   CPU%    CPU Time"
          ps auxww | sed -ne '/bladeenc/p' -e '/8hz-mp3/p' -e '/l3enc/p' -e '/lame/p' -e '/xingmp3enc/p' -e '/mp3enc/p' -e '/oggenc/p' -e '/gogo/p' | awk '$11 !~ /sed/ { print $11"    " $2"   " $3"    " $10 }'
          STATUS=`wc -l ${TEMPDIR}/encode | awk '{ print $1 }'`
          STATUS=`expr ${STATUS} - 1`
          CURRENT=`sed -ne '1p' ${TEMPDIR}/encode`
          echo ; echo "Currently" ${CURRENT} "is being encoded"
          case ${STATUS} in
               0)
                    echo ; echo "No more songs are in the queue"
                    ;;
               1)
                    echo ; echo "This 1 song still needs to be encoded:"
                    ;;
               *)
                    echo ; echo "These" ${STATUS} "songs still need to be encoded:"
                    ;;
          esac

          #Top line of encode file is the song currently being encoded so to print only the ones that
          #still need to be encoded we print from line 2 to end of file ($)
          sed -ne '2,$p' ${TEMPDIR}/encode
          echo ; echo "Press enter to continue" ; read continue
     fi

     return
}

#Simply displays the encode.log...
mainV()
{
     ABORT=1
     if [ -f ${TEMPDIR}/encode.log ] ;
     then
          cat ${TEMPDIR}/encode.log
          echo ; echo ; echo "Press <enter> to continue" ; read continue
          ABORT=0
    else
          echo ; echo "There is no encode.log file to view"
          echo ; echo "Press <enter> to continue" ; read continue
          ABORT=0
    fi

    return
}

#Deletes the encode.log file with an appropriate warning
mainDEL()
{
     if [ -f ${TEMPDIR}/lock.encode ] ;
     then
          echo ; echo "Deleting the encode log while an encode process is running will keep any more info from being written to the log"
          echo "file about the current song being encoded. The next song in the queue will then resume writing to the log file."
          echo ; echo -n "Do you still want to do this [y/N]? "
          read choice

          if [ "${choice}" = "y" ] ;
          then
               rm -f ${TEMPDIR}/encode.log
          fi
     else
          rm -f ${TEMPDIR}/encode.log
     fi

     return
}

#Calls preferMenu() which returns here...main1() returns to mainMenu()
main1()
{
     preferMenu
     return
}

#Calls the appropriate naming method...either getcddb() or manual()..also set confirm appropriately for
#cddb or manual naming...
main2()
{
     if [ "${METHOD}" = "manual" ]
     then
          manual
     fi
     if [ "${METHOD}" = "wget" ]
     then
          wget_cddb
     fi
     if [ "${METHOD}" = "cda" ]
     then
          cda_cddb
     fi

     #call cleantemp() to remove temp files between each CD...except encode, encode.log and encode.id3
     cleantemp

     return
}

#Check system for supported software...thanks to Keenan Brock for submitting some changes
#that cleaned up and shortened this function
main3()
{
     RIPPERS="cdparanoia dagrab cdda2wav tosha"
     ENCODERS="bladeenc 8hz-mp3 l3enc lame xingmp3enc mp3enc oggenc gogo"
     TAGTOOLS="id3ren mp3info"
     MAND="sed awk cut tr"
     MISC="eject dialog cda"
     WGET="wget discid"

     echo ; echo -e "\033[1mMANDATORY TOOLS!\033[0m"
     searchFor ${MAND}

     echo ; echo -e "\033[1mRIPPERS...\033[0m"
     searchFor ${RIPPERS}

     echo ; echo -e "\033[1mENCODERS...\033[0m"
     searchFor ${ENCODERS}

     echo ; echo -e "\033[1mTAGTOOLS...\033[0m"
     searchFor ${TAGTOOLS}

     echo ; echo -e "\033[1mMISC...\033[0m"
     searchFor ${MISC}

     echo ; echo -e "\033[1mTOOLS REQUIRED TO USE \"wget\" FOR CDDB ACCESS...\033[0m"
     searchFor ${WGET}
     echo ; echo "NOTE: To use \"wget\" to access CDDB through http you must have read permissions on your chosen CD-ROM"
     echo "device so \"discid\" can read the table of contents to calculate the Disc ID."

     echo ; echo "Please press <enter> to continue"
     read cont

     return
}

#Display files in working directory
main4()
{
     ls ${SAVETO}/
     echo
     echo "Hit enter to continue" ; read continue
     return
}

#Show the about information in a dialog box...don't know much about dialog, only know enough
#to do this :-)
main5()
{
    echo "              RipEnc ${VERSION} By Michael J. Parmeley" >> ${TEMPDIR}/tmprip
    echo >> ${TEMPDIR}/tmprip
    echo "                      mjparme@asde.net" >> ${TEMPDIR}/tmprip
    echo >> ${TEMPDIR}/tmprip
    echo "              http://www.asde.net/~mjparme/index.htm" >> ${TEMPDIR}/tmprip
    echo >> ${TEMPDIR}/tmprip
    echo "Thanks to the following people for some great ideas and/or code" >> ${TEMPDIR}/tmprip
    echo "                        Bryan Mayland                " >> ${TEMPDIR}/tmprip
    echo "                       Vijay Bharadwaj               " >> ${TEMPDIR}/tmprip
    echo "                       Jason Willoughby              " >> ${TEMPDIR}/tmprip
    echo "                         Oyvind Moll                 " >> ${TEMPDIR}/tmprip
    echo "                         Justin Lee                  " >> ${TEMPDIR}/tmprip
    echo "                         Evan Jones                  " >> ${TEMPDIR}/tmprip
    echo "                         Devon Jones                 " >> ${TEMPDIR}/tmprip
    echo "                        Keenan Brock                 " >> ${TEMPDIR}/tmprip
    dialog --backtitle "About RipEnc ${VERSION}" --msgbox "`cat ${TEMPDIR}/tmprip`" 20 67
    rm ${TEMPDIR}/tmprip
    return
}

#Exit RipEnc
main6()
{
    saverc
    cleantemp
    exit 0
}

#Set the working directory...all manually inputted options will reset
#to old value if prompt is left empty
option1()
{
   OLDSAVETO=${SAVETO}
   echo
   echo -n "Enter your working directory: "
   read SAVETO
   TEMPSAVETO=${SAVETO}
   testsaveto
   return
}

#Choose encoder
option2()
{
    echo
    echo "1) bladeenc"
    echo "2) 8hz-mp3"
    echo "3) l3enc"
    echo "4) lame"
    echo "5) xingmp3enc"
    echo "6) mp3enc"
    echo "7) oggenc"
    echo "8) gogo  (Not implemented yet!)"
    echo "9) Do not automatically start encoding"
    echo -n "? " ; read opt
    if [ "${opt}" = "1" ]
    then
         ENCODER=bladeenc
    fi
    if [ "${opt}" = "2" ]
    then
         ENCODER=8hz-mp3
    fi
    if [ "${opt}" = "3" ]
    then
         ENCODER=l3enc
    fi
    if [ "${opt}" = "4" ]
    then
         ENCODER=lame
    fi
    if [ "${opt}" = "5" ]
    then
         ENCODER=xingmp3enc
    fi
    if [ "${opt}" = "6" ]
    then
         ENCODER=mp3enc
    fi
    if [ "${opt}" = "7" ]
    then
         ENCODER=oggenc
         #oggenc has its own tagging system for the Ogg format...need to turn off the id3 tagger
         ID3TOOL=none
    fi
    if [ "${opt}" = "8" ]
    then
         ENCODER=gogo
    fi
    if [ "${opt}" = "9" ]
    then
         ENCODER=none
    fi
    
    #These next few lines deal with the fact that l3enc accepts bitrates as 5 or 6 digits instead of 3
    #(i.e. 128000 instead of 128 or 64000 instead of 64) like the other encoders
    #Just divide or multiply by 1000 as appropriate
    if [ "${ENCODER}" = "bladeenc" -o "${ENCODER}" = "8hz-mp3" -o "${ENCODER}" = "lame" -o "${ENCODER}" = "l3enc" -o "${ENCODER}" = "xingmp3enc" -o "${ENCODER}" = "mp3enc" -o "${ENCODER}" = "oggenc" -o "${ENCODER}" = "gogo"] && [ ${BITRATE} -gt 999 ]  ;
    then
         BITRATE=`expr ${BITRATE} / 1000`
    fi
    if [ "${ENCODER}" = "l3enc" ] && [ ${BITRATE} -le 999 ] ;
    then
         BITRATE=`expr ${BITRATE} \* 1000`
    fi

    return
}

#Choose the Ripper
option3()
{
    echo
    echo "1) cdparanoia"
    echo "2) cdda2wav"
    echo "3) tosha"
    echo "4) dagrab"
    echo "5) none (assume wavs exist and/or wav files need to be encoded)"
    echo -n "? " ; read ch
    if [ "${ch}" = "1" ] ;
    then
         RIPPER=cdparanoia
    fi
    if [ "${ch}" = "2" ] ;
    then
         RIPPER=cdda2wav
    fi
    if [ "${ch}" = "3" ] ;
    then
         RIPPER=tosha
    fi
    if [ "${ch}" = "4" ]  ;
    then
         RIPPER=dagrab
    fi
    if [ "${ch}" = "5" ]  ;
    then
         RIPPER=none
    fi

    return
}

#Choose the id3 tag tool
option4()
{
     if [ "${ENCODER}" = "oggenc" ]
     then
          echo ; echo "You have selected oggenc as your encoder which has its own tagging system. You do not need to use an id3 tagging tool."
          echo "RipEnc will pass the tag information to oggenc during the encoding process (doesn't work yet actually)."
          echo
          echo "Hit <enter> to continue"
          read cont

          return
     fi

     echo ; echo "Some versions of mp3info do not support the command line options.  If you have one of these"
     echo  "versions please upgrade to the newest version!"
     echo
     echo "1) mp3info"
     echo "2) id3ren"
     echo "3) none"
     echo -n "? " ; read ch
     if [ "${ch}" = "1" ] ;
     then
          ID3TOOL=mp3info
     fi
     if [ "${ch}" = "2" ] ;
     then
          ID3TOOL=id3ren
     fi
     if [ "${ch}" = "3" ] ;
     then
          ID3TOOL=none
     fi

     return
}

#Lets user select nameing method...eight manual or CDDB with cda or wget
option5()
{
    METHODTEMP=${METHOD}

    echo
    echo "1) Manual Naming"
    echo "2) CDDB with wget"
    echo "3) CDDB with cda"
    echo -n "? " ; read ch

    if [ "${ch}" = "1" ] ;
    then
         METHOD=manual
    fi
    if [ "${ch}" = "2" ] ;
    then
         METHOD=wget

         echo ; echo "You must have read permissions on your CD-ROM device to use wget (so the Disc ID program can calculate the discid)."
         echo "If you are using wget and RipEnc doesn't retrieve the CDDB info you may want to make sure you have read permissions"
         echo "on your chosen CD-ROM device!"
         echo ; echo "Hit <enter> to continue" ; read continue

         #Check to see if "wget" is installed on the system and is in the path
         which wget 1>& /dev/null
         checkForWget=`echo $?`

         if [ $checkForWget -eq 1 ]
         then
              echo ; echo "Can not find \"wget\" in your PATH. You will need to download it or add its location to your PATH!"
              echo ; echo "Hit <enter> to continue" ; read continue
              METHOD=${METHODTEMP}
         fi

         #Check to see if "discid" the Disc ID calculation utility included with RipEnc is in the path
         which discid 1>& /dev/null
         checkForDiscid=`echo $?`

         if [ ${checkForDiscid} -eq 1 ]
         then
              echo
              echo "Can not find \"discid\" in your PATH. This is the Disc ID calculation utility that should"
              echo "have been included with RipEnc. This is required to use wget for CDDB lookups."
              echo ; echo "Hit <enter> to continue." ; read continue
              METHOD=${METHODTEMP}
         fi
    fi
    if [ "${ch}" = "3" ] ;
    then
         METHOD=cda

         which cda 1>& /dev/null
         checkForCda=`echo $?`

         if [ $checkForCda -eq 1 ]
         then
              echo ; echo "Can not find \"cda\" in your PATH. You will need to download it (it is in the XMCD package) or add its location to your PATH!"
              echo ; echo "Hit <enter> to continue" ; read continue
              METHOD=${METHODTEMP}
         fi
    fi

    return
}

#Change the name of the CDDB server
option5a()
{
     SERVERTEMP=${SERVER}

     echo ; echo -n "Please enter the name of the CDDB server: "
     read SERVER

     if [ "${SERVER}" = "" ]
     then
          SERVER=${SERVERTEMP}
     fi
}

#Change the server's CGI directory
option5b()
{
     CGITEMP=${CGI}

     echo ; echo "You shouldn't change this unless you are absolutely sure your chosen server uses"
     echo "a different value than the default!  Do not add the trailing / to CGI path name."
     echo ; echo -n "Please enter the CGI path on the server: "
     read CGI

     if [ "${CGI}" = "" ]
     then
          CGI=${CGITEMP}
     fi
}

#Change the domain name
option5c()
{
     DOMAINTEMP=${DOMAIN}

     echo ; echo -n "Please enter your domain name (used in CDDB lookups): "
     read DOMAIN

     if [ "${DOMAIN}" = "" ]
     then
          DOMAIN=${DOMAINTEMP}
     fi
}

#Set the XMCD library variable
option6()
{
     XMCDTEMP=${XMCDLIB}
     echo ; echo -n "Please enter the path to your xmcd library directory: "
     read XMCDLIB
     if [ ! -d ${XMCDLIB} ] ;
     then
          echo "That directory does not seem to exist"
          echo "Hit enter to continue" ; read continue
          XMCDLIB=${XMCDTEMP}
     fi
     if [ "${XMCDLIB}" = "" ] ;
     then
          XMCDLIB=${XMCDTEMP}
     fi

     return
}
                     
#Choose a naming convention...NCONVENT is just for the users sake in the preferences menu
#the value of the select variable slects the naming convention in rip()
option7()
{
     echo ; echo -e "\033[1mNOTE: Option 5 and 6 can not be used with various artist CD's\033[0m" ; echo
     echo "1) artist-name_of_song.mp3"
     echo "2) track#-artist-name_of_song.mp3"
     echo "3) Artist-Name_Of_Song.mp3 ( note the case changes )"
     echo "4) track#-Artist-Name_Of_Song.mp3"
     echo "5) artist--album/track#-name_of_song.mp3"
     echo "6) artist/album/track#-name_of_song.mp3"
     echo "7) Artist-Album-track#-Name_Of_Song.mp3"
     echo -n "? " ; read select
     if [ "${select}" = "1" ]  ;
     then
          NCONVENT=artist-name_of_song.mp3
     fi
     if [ "${select}" = "2" ] ;
     then
          NCONVENT=track#-artist-name_of_song.mp3
     fi
     if [ "${select}" = "3" ]  ;
     then
          NCONVENT=Artist-Name_Of_Song.mp3
     fi
     if [ "${select}" = "4" ] ;
     then
          NCONVENT=track#-Artist-Name_Of_Song.mp3
     fi
     if [ "${select}" = "5" ] ;
     then
          NCONVENT=artist--album/track#-name_of_song.mp3
     fi
     if [ "${select}" = "6" ] ;
     then
          NCONVENT=artist/album/track#-name_of_song.mp3
     fi
     if [ "${select}" = "7" ] ;
     then
          NCONVENT=Artist-Album-track#-Name_Of_Song.mp3
     fi

     return
}
                        
#Choose to rip the whole CD or not
option8()
{
     if [ "${METHOD}" = "manual" ] ;
     then
          echo "You are using Manual naming. Changing this option has no effect."
          echo "Hit enter to continue" ; read continue
     else
          if [ "${WHOLE}" = "no" ] ;
          then
               WHOLE=yes
          else
               WHOLE=no
          fi
     fi

     return
}

#Choose whether to use small hard drive option or not
option9()
{
     if [ "${SMALL}" = "no" ] ;
     then
          echo ; echo "Setting this option to YES makes RipEnc rip one song and then encode that song"
          echo "before ripping another one.  This is handy if you have a small hard drive and do"
          echo "not have room for a whole CD on your hard drive."
          echo ; echo "Press <enter> to continue" ; read continue
     fi

     if [ "${SMALL}" = "no" ] ;
     then
          SMALL=yes
     else
           SMALL=no
     fi

      return
}

#Select Cd-Rom device
option10()
{
     TEMPDEVICE=${DEVICE}

     echo ; echo -n "Enter full path of device: "
     read DEVICE

     if [ ! -e ${DEVICE} ] ;
     then
          echo ${DEVICE} "does not exist...hit enter to continue"
          read continue
          DEVICE=${TEMPDEVICE}
     fi

     if [ "${DEVICE}" = "" ] ;
     then
          DEVICE=${TEMPDEVICE}
     fi

     return
}                      

#Toggle whether to eject CD after ripping is complete
option11()
{
     if [ "${EJECT}" = "no" ]
     then
          EJECT=yes
     else
          EJECT=no
     fi

     which eject >& /dev/null
     checkForEject=`echo $?`

     which cda >& /dev/null
     checkForCda=`echo $?`

     # sh and bash return 1 if a command us UNSUCCESSFUL and they return 0 if it was SUCCESSFUL
     #A little different that what you might expect if you program in other languages
     if [ ${checkForEject} -eq 1 ]
     then
          if [ ${checkForCda} -eq 1 ]
          then
               #Tell user we can't eject Cd and set EJECT=no
               echo ; echo "Can't find either of the two tools that can eject the CD in your PATH (eject or cda)!"
               EJECT=no
               echo "Hit <enter> to continue" ; read continue
          else
               #Use cda for ejecting CD
               foundEjectTool=cda
          fi
     else
          #Use eject for ejecting CD
          foundEjectTool=eject
     fi

     if [ "${EJECT}" = "no" ]
     then
          foundEjectTool=""
     fi

     return
}

#Choose the bitrate to encode the mp3's as
option12()
{
     TEMPBITRATE=${BITRATE}
     echo ; echo -n "Type your Bitrate (only enter two or three digits ie 64, 128, 256, etc): "
     read BITRATE

     #Converts the inputted bitrate to the format for l3enc if l3enc is the selected encoder
     if [ "${ENCODER}" = "l3enc" ] ;
     then
          ZERO=000
          BITRATE=${BITRATE}${ZERO}
     fi

     if [ "${BITRATE}" = "" ] ;
     then
          BITRATE=${TEMPBITRATE}
     fi

     return
}

#Set a VERSION variable so it makes it easier to update the version number
VERSION=1.1

#RipEnc starts execution here...starts with some housekeeping and reading in defaults values which
#will be overidden by values in the ripencrc file if it exists
setDefaults
checkoldrc
checkforsed
cleantemp

#Reads in options from ripencrc if it exists...overrides defaults
if [ -f ${RCDIR}/ripencrc ] ;
then
     . ${RCDIR}/ripencrc
     RCREAD=1
     testsaveto
fi

#Now call the mainMenu()...all other execution will take place in the functions
#exiting with option 5 from the main menu will exit normally (exit 0), exiting
#with CTRL-C or other adnormal exit will result in a exit 1 from forcequit()
mainMenu
