#!/bin/bash
#
# Copyright (C) by Stefano Falsetto
# e-mail contact ....: mailto:stefko5@inwind.it
#
#    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
#
#
# This script converts a list of audio files in another format
# and eventually record these files on a cd.
#
# WARNING: This script is bash2.x compatible.
#




TEMPDIR="$HOME/tmp/$(basename $0).$ "
[ ! -d $TEMPDIR ] && mkdir -p $TEMPDIR
TEMPDATA=$TEMPDIR/tempdata.$$
TEMPNOMEF=$TEMPDIR/tempnomef.$$
SONGDATA=$TEMPDIR/songdata.$$
TMPTOC=$TEMPDIR/tocdata.$$
FILETEMPSONG=$TEMPDIR/filetempsong.$$
WROTEFILES=$TEMPDIR/wrotefiles.$$
#TMP_PIPE=$TEMPDIR/piped_data.$$

[ $(whoami) != "root" ] && PATH="$PATH:$PWD"
trap 'rm -Rf $TEMPDIR; exit $USCITA' 0
trap 'lechoc STDERR "Terminated by interrupt signal!"; exit 99' 2
USCITA=0

if [ -r $HOME/.mp3do.rc ]; then 
  . $HOME/.mp3do.rc
elif [ -r /etc/mp3do.rc ]; then
  . /etc/mp3do.rc
else
  lechoc STDERR  "No configuration file found. Run ConfigMP3do first"
  USCITA=255; exit $USCITA
fi


# 
# BEGIN INTERNAL VARIABLES: DON'T MODIFY!
#
TOCFILE=""
SONGFILE=""
VERSION=4.0-rc10
SPOOLDIR="."

# Controlli iniziali
ERR_NO_PARAM=1
ERR_NO_DECODER=2

#Nel parsing
ERR_NO_READFILE=101
ERR_NO_SUPP_TYPE=102
ERR_NO_TYPE=103
ERR_BAD_PARAM=104
ERR_TOC_EXIST=105
ERR_NO_TOFCILE=106
ERR_BAD_NORM_METHOD=107
ERR_BAD_WRITER=108
ERR_BAD_SPEED=109

# Nei sanity checks
ERR_NEED_SF=201
ERR_CANT_NORM_CDR=202
ERR_NO_VALID_SONG=203

# Nel calcolo tempo
ERR_OVERTIME=301

# Nella decoding phase
ERR_NOEXIST=350

# Nella normal writing phase
ERR_TOC_ERR=401
ERR_BAD_WRITE=402
ERR_NO_ATIP=403

#
# END INTERNAL VARIABLES DEFINITION
#

banner() {
  if [ -z $1 ]; then
    lechoc BOLD  "This is MP3do ver %s" "$VERSION"
    lechoc BOLD  "Copyright (C) 2001 by Stefano Falsetto"
    lechoc BOLD  "MP3do comes with ABSOLUTELY NO WARRANTY"
  else 
    echoc BOLD "This is free software, and you are welcome to redistribute it"
    echoc BOLD "under certain conditions; This program is distributed in the"
    echoc BOLD "hope that it will be useful, but WITHOUT ANY WARRANTY; without"
    echoc BOLD "even the implied warranty of MERCHANTABILITY or FITNESS FOR A"
    echoc BOLD "PARTICULAR PURPOSE. See the GNU General Public License"
    echoc BOLD "for more details."
  fi
  echo
}

quest() {
  local Q

  if [ -z $4 ]; then
    lechoc STDERR  "There are no valid return valules!" 
    exit -999;
  fi
  # TODO parametrize default reponse
  while [ 0 ]; do
    lechoc CYAN -n  "%s (Y/N) [Y] " "$1"
    read Q
    case "$Q" in
      ""|Y|y|S|s)
        lechoc YELLOW "$2"
        return $4
        break
        ;;
      N|n)
        lechoc YELLOW "$3"
        return $5
        break
        ;;
      *)
        lechoc CYAN  "Valid reponses: Y or N"
        ;;
    esac
  done
}

writecd() {

# Preparing parameters...
  local WRITER="$1"
  local OPZDUMMY="$2"
  local OPZ="$3"
  shift 3
  local OTHER="$@"

  while [ 0 ]; do
    COMMAND="$WRITER $OPZDUMMY $OPZ $OTHER"
    $COMMAND
    if [ $? -ne 0 ]; then
      lechoc STDERR  "CD has not been properly writed!" 
      return 1
    else
      if [ -z "$OPZDUMMY" ]; then
        lechoc YELLOW  "Sucessfully Terminated. :-)"
        return 0
      else
        lechoc CYAN  "Dummy write successfully terminated. Will execute real write..."
        OPZDUMMY=""
      fi
    fi
  done
}

min_sec_msec() {
  # isoliamo i vari pezzi
  MINUTI=${1:0:2}
  SECONDI=${1:3:2}
  MSEC=${1:6:2}
}

estrai_tempo() {

  extract_time_$2 "$1"

  WCL="$RET_WCL"
  TEMPOSONG="$TS"

  if [ "$WCL" -ne 0 ]; then
    lechoc GREEN  " WARNING: This file has some error"
  fi

  # Now this function return only $TEMPOSONG

}

calcola_tempo() {

  TTOT="00:00:00"

  local i=0
  while [ $i -lt ${#SONG[@]} ]; do
    min_sec_msec ${TIME[$i]}
  
    TOTMSEC=$[ 10#$TOTMSEC + 10#$MSEC ];
    if [ $TOTMSEC -gt 99 ]; then
      SECONDI=$[ 10#$SECONDI + 1];
      TOTMSEC=$[ 10#$TOTMSEC - 100 ];
    fi
  
    TOTSEC=$[ 10#$TOTSEC + 10#$SECONDI ];
    if [ $TOTSEC -gt 59 ]; then
      MINUTI=$[ 10#$MINUTI + 1 ];
      TOTSEC=$[ 10#$TOTSEC - 60 ];
    fi
    
    TOTMIN=$[ 10#$TOTMIN + 10#$MINUTI ];
    i=$[ i + 1 ]
  done

  TTOT=$(echo "$TOTMIN:$TOTSEC.$TOTMSEC");

}

sintassi() {
  echo  "  Syntax: MP3do <options>"
  echo  "  -h [<plugin-name>], --help [<plugin-name>]"
  echo  "      Display this help screen. If a plugin-name is given"
  echo  "      will be displayed only help for plugin."
  echo  "  -V, --version"
  echo  "      Display version, disclamier and exit"
  echo  "  -f <filename>, --file <filename>"
  echo  "      Audio files are read from this file."
  echo  "  --spooldir <dir>"
  echo  "      Directory to use to write decoded files."
  echo  "  -t <format-file>, --type <format-file>"
  echo  "      Type of file that will be used to decode audio files."
  echo  "  -s <filelist>, --songs <filelist>"
  echo  "      Instead of using -f option you can specify each file one-by-one."
  echo  "  --toc <tocfile>"
  echo  "      Tocfile (cdrdao compatible) created while decoding audio files."
  echo  "  -T, --timesum"
  echo  "      Compute sum of minutes and seconds of all audio files and exit."
  echo  "  -n <mix|batch>, --normalize <mix|batch>"
  echo  "      Normalize all the song with the method specified."
  echo  "      Default method is $DEFNORM"
  echo  "  --no-sox"
  echo  "      Force deactivation of auto-conversion feature"
  echo  "  --trust-extension"
  echo  "      Check for file type only using extensions"
  echo

  if [ "$(whoami)" = "$PRIVUSER" ]; then
    echo  "Options for user $PRIVUSER:"

    if [ ! -z "$CDRECORD" ] || [ ! -z "$CDRDAO" ]; then
      (
      if [ ! -z "$CDRECORD" ] && [ ! -z "$CDRDAO" ]; then
        choice="[<cdrdao|cdrecord>]"
      fi
      echo  "-w $choice, --write $choice"
      echo  "    To write a cd with the previously converted files." 
      [ -z $choice ] || echo  "    Default: $(basename $DEFWRITER)"
      )
  
      if [ ! -z "$CDRECORD" ]; then
        echo  "--on-the-fly"
        echo  "    Burn a cd 'on the fly' while decoding audio files."
        echo  "    (Implies -w cdrecord -t cdr)"
        echo  "--one-by-one"
        echo  "    Decode and burn one song at time. (Implies -w cdrecord)"
      fi
      echo  "--speed <write-speed>"
      echo  "    Set writing speed. Must be a valid number between 1 and $MAXWRITESPEED"
      echo  "--eject"
      echo  "    Eject CD after writing. Some Devices (e.g. Philips) need"
      echo  "    to eject the medium before creating a new disk even after"
      echo  "    a dummy write"
      echo  "-r, --nodummy"
      echo  "    Don't ask to perform a dummy write before a real burning process"
      echo  "    (Implies -w)"
      echo  "-d, --purge"
      echo  "    Delete converted files from actual dir after a well terminated"
      echo  "    burning process. (Implies -w)"
    fi
  fi

  echo
  echo  "Options for plugins:"
  for PLUG in $PLUGINS_WITH_PARAMETERS; do
    syntax_$PLUG
  done

  echo
  echo  "  Supported input audio file formats:"
  echo  "  $SUPPORTED_FORMATS"
  echo
  echo  "  Supported output audio file formats (used with -t option):"
  for PLUG in $AUDIO_PLUGINS; do
   printf "  %-10s : " "$PLUG"
   eval echo "\${OUTPUT_FORMATS_${PLUG}[@]}"
  done
  echo
  if [ ! -z "$1" ]; then
    USCITA=$1
    exit $USCITA
  fi
}

numbered_name() {
  # 1  il numero, 2  il nome file

  # Strips longest substring between two / from beginning of $2
  #local FILENAME=${2##\/*\/}
  local FILENAME=$(basename "$2")
  if [ $1 -lt 10 ]; then
    nomef=$(echo "0$1-$FILENAME"|tr " " "_")
  else
    nomef=$(echo "$1-$FILENAME"|tr " " "_")
  fi
}

find_param () {
  local f_param=
  local indice=
  # To handle short, long and "anomal" parameters
  if [ $(expr "$1" : ".*:.*") -eq ${#1} ]; then
    f_param="$(echo "$1"|cut -d':' -f1):"
  else
    f_param=$1
  fi
  indice=$(expr "$ALL_PARAMETERS_PLUGINS|" : ".*|$f_param|")
  if [ $indice -ne 0 ]; then
    indice=$[ indice - 2 ]
    parse_param_${ARR_PLUG_PARAM[$indice]} "$1" "$2"
    RETC=$?
    if [ $RETC -eq 1 ]; then
      return $SHIFT
    elif [ $RETC -eq -1 ]; then
      lechoc STDERR "%s: %s" "$PLUG" "$STRERR"
      exit $USCITA
    fi
  fi
  return 0
}

make_plug_param() {
  local count=0
  for i in $LIST_PLUG_PARAM; do
    indice=${INDEX_PLUG_PARAM[$count]}
    ARR_PLUG_PARAM[$indice]=$i
    count=$[ count + 1 ]
  done
}

###############################################################################
# Begin main                                                                  #
###############################################################################

banner

# Begin plugins area

lechoc CYAN -n  "Loading audio plugins..."
for P in $AUDIO_PLUGINS; do
  # Prevent multiple inclusion:
  plugin_present_$P 2>/dev/null
  if [ $? -ne 0 ]; then
    . $PLUGINDIR/general/$P
  fi
done
lechoc CYAN  "Done"

lechoc CYAN -n  "Loading phase"
for nphase in 1 2 3 4; do
  lechoc CYAN -n " $nphase"
  P_PHASES= 
  for WHERE in BEGIN END; do
    P_PHASES=$(eval echo \${PHASE${nphase}_${WHERE}[@]})
    for PLUG in $P_PHASES; do
      . $PLUGINDIR/phase$nphase/$PLUG
    done
  done
done
lechoc CYAN  " plugins done."
echo
# End plugins area

make_plug_param


if [ $# -eq 0 ]; then
  lechoc STDERR  "No parameters specified!" 
  sintassi 1
fi

plugin_present_sox 2>/dev/null
if [ $? -ne 0 ]; then
  lechoc GREEN  "WARNING: \
  Can't find sox plugin. Perhaps you must properly configure \
  plugins or you must install sox. \
  Will run without auto-conversion features."
  echo
fi

(
FIND_DECODER=
for PLUG in $AUDIO_PLUGINS; do
  FIND_DECODER="$FIND_DECODER ${PLUG}_DECODER"
done
if [ -z "$FIND_DECODER" ]; then
  lechoc STDERR  "Can't find ANY decoder program. Perhaps you must properly configure plugins" 
  USCITA=$ERR_NO_DECODER; exit $USCITA
fi
)
EXIT_SS=$?
if [ $EXIT_SS -ne 0 ]; then
  exit $EXIT_SS
fi

# Parsing della linea di comando:
while [ $# -ne 0 ]; do
  SHIFT=0
  RETC=0
  index=0
  find_param "$1" "$2"
  shift $?
  #for PLUG in $PLUGINS_WITH_PARAMETERS; do
  #  parse_param_$PLUG "$1" "$2"
  #  RETC=$?
  #  if [ $RETC -eq 1 ]; then
  #    break
  #  elif [ $RETC -eq -1 ]; then
  #    lechoc STDERR "%s: %s" "$PLUG" "$STRERR"
  #    exit $USCITA
  #  fi
  #  index=$[ index + 1 ]
  #done
  #shift $SHIFT
  if [ $RETC -eq 0  ]; then
    case "$1" in
    -h|--help)
         if [ ! -z "$2" ] && [ "$(expr "$2" : "-*")" -eq 0 ]; then
           (
           for i in $PLUGINS_WITH_PARAMETERS; do
             if [ "$i" = "$2" ]; then
               echo  "Plugin $2 syntax:"
               syntax_$2
               echo
               exit 0
             fi
           done
           echo  "Plugin $2 not present or not handle parameters"
           exit $ERR_BAD_PARAM
           )
           exit $?
         else
           sintassi 0
         fi
         ;;
    --spooldir)
         if [ ! -z "$2" ] && [ -d "$2" ]; then
           if [ "${2:0:1}" = "/" ] || [ "${2:0:2}" = "./" ]; then
             SPOOLDIR="$2"
           else
             SPOOLDIR="./$2"
           fi
           
           shift
         else
           lechoc STDERR "Invalid spool dir : %s" "$2"
           USCITA=$ERR_BAD_PARAM; exit $USCITA
         fi
         ;;
    -f|--file)
         if [ ! -z "$2" ] && [ "$(expr "$2" : "-*")" -eq 0 ]; then
           if [ ! -r "$2" ]; then
             lechoc STDERR  "File %s does'nt exist or is'nt readable" "$2"
             USCITA=$ERR_FILE_NOEXIST; exit $USCITA
           else
             sed -e '/^#/d' -e '/^$/d' "$2" >$TEMPNOMEF
             SONGFILE=$TEMPNOMEF
             shift
           fi
         else
           lechoc STDERR  "No filename specified!"
           USCITA=$ERR_NO_FILENAME; exit $USCITA
         fi
         ;;
    --toc)
         if [ ! -z "$2" ] && [ "$(expr "$2" : "-*")" -eq 0 ]; then
           if [ ! -e "$2" ]; then
             TOCFILE="$2"
             shift
           else
             lechoc STDERR  "TOC file already exist!"
             USCITA=$ERR_TOC_EXIST; exit $USCITA
           fi
         else
           lechoc STDERR  "No TOC file specified!"
           USCITA=$ERR_NO_TOFCILE; exit $USCITA
         fi
         ;;
    -t|--type)
         # If -t is the last parameter or if type is'nt specified:
         if [ -z "$2" ] || [ ${2:0:1} = "-" ]; then
           lechoc STDERR  "No output format type specified!"
           USCITA=$ERR_NO_TYPE; exit $USCITA
         fi
         TIPO=$(echo "$2"|tr A-Z a-z)
         T_SUPP=
         for PLUG in $AUDIO_PLUGINS; do
           parse_param_t_$PLUG "$TIPO" #2>/dev/null
         done
         
         # This error never happens if plugins where well created...
         if [ -z "$T_SUPP" ]; then
           lechoc STDERR  "Type %s not supported" "$2"
            USCITA=$ERR_NO_SUPP_TYPE; exit $USCITA
         fi
         
         shift 
         ;;
    -s|--song)
         SONGFILE=$TEMPDATA
         > $TEMPDATA
         ;;
    -T|--timesum)
         ONLYTIME=1
         ;;
    -V|--version)
         banner 1
         USCITA=0; exit 0
         ;;
    --no-sox)
         SOX=""
         ;;
    --trust-extension)
         TRUST_EXT=1
         ;;
    *)
       if [ "$USER" != "$PRIVUSER" ]; then
         if [ "$SONGFILE" = "$TEMPDATA" ]; then
           if [ "$(expr "$1" : "-*")" -ne 0 ]; then
             lechoc STDERR  "Bad parameter: %s" "$1"
             USCITA=$ERR_BAD_PARAM; exit $USCITA
           else
             echo "$1">>"$TEMPDATA"
           fi
         else
           lechoc STDERR  "Bad parameter: %s" "$1"
           USCITA=$ERR_BAD_PARAM; exit $USCITA
         fi
       else
         case "$1" in 
           -w|--writer)
               if [ -z "$2" ]; then
                 WRITER=$DEFWRITER
                 break
               fi
               case "$2" in
                 cdrecord)
                    if [ -z "$CDRECORD" ]; then
                      lechoc STDERR "MP3do is configured to use only cdrdao!"
                      USCITA=$ERR_BAD_WRITER; exit $USCITA
                    fi
                    WRITER=$CDRECORD
                    shift
                    ;;
                 cdrdao)
                    if [ -z "$CDRDAO" ]; then
                      lechoc STDERR "MP3do is configured to use only cdrecord!"
                      USCITA=$ERR_BAD_WRITER; exit $USCITA
                    fi
                    WRITER=$CDRDAO
                    shift
                    ;;
                 -*)
                    WRITER=$DEFWRITER
                    ;;
                 *)
                    lechoc STDERR  "Unknown writer %s!" "$2"
                    USCITA=$ERR_BAD_WRITER; exit $USCITA
                    ;;
               esac
               ;;
           -r|--nodummy)
               NODUMMY=1
               ;;
           -d|--purge)
               DELFILES=1
               ;;
           --on-the-fly)
               if [ ! -z "$CDRECORD" ]; then
                 ALVOLO=1
                 WRITER=$CDRECORD
               fi
               ;;
           --one-by-one)
               if [ ! -z "$CDRECORD" ]; then
                 UNOAUNO=1
                 WRITER=$CDRECORD
               fi
               ;;
           --speed)
               if [ -z "$2" ] || [ "${2:0:1}" = "-" ]; then
                 lechoc STDERR  "Bad writing speed!"
                 USCITA=$ERR_BAD_SPEED; exit $USCITA
               fi
               #if [ $2 -gt 0 ] 2>/dev/null && [ $2 -le $MAXWRITESPEED ]
               if [ $(expr "$2" : "[[:digit:]]*") -eq ${#2} ] && \
                  [ $2 -le $MAXWRITESPEED ]; then
                 OPZCDRECORD="$OPZCDRECORD speed=$2"
                 OPZCDRDAO="$OPZCDRDAO --speed $2"
               else
                 lechoc STDERR  "Bad writing speed: $2"
                 USCITA=$ERR_BAD_SPEED; exit $USCITA
               fi
               shift
               ;;
           --eject)
               OPZCDRECORD="$OPZCDRECORD -eject"
               OPZCDRDAO="$OPZCDRDAO --eject"
               EJECT_CD="-eject"
               ;;
           *)
               if [ "$SONGFILE" = "$TEMPDATA" ]; then
                 echo "$1">>"$TEMPDATA"
               else
                 lechoc STDERR  "Bad parameter: %s" "$1"
                 USCITA=$ERR_BAD_PARAM; exit $USCITA
               fi
               ;;
         esac
       fi
       ;;
    esac
    shift
  fi
done


# Local Sanity checks...

if [ -z $SONGFILE ]; then 
  lechoc STDERR  "Need parameter -s or -f" 
  USCITA=$ERR_NEED_SF; exit $USCITA
fi

if [ -z "$T_SUPP" ]; then
  T_SUPP="wav"
fi

if [ ! -z "$UNOAUNO" -o ! -z "$ALVOLO" ]; then
  if [ "$WRITER" = "$CDRDAO" ]; then
    lechoc GREEN  "WARNING:"
    lechoc GREEN  "--one-by-one and --on-the-fly options implies -w cdrecord"
    lechoc GREEN  "Using -w cdrecord"
    WRITER=$CDRECORD
  fi
  # Silently ignoring --eject
  OPZCDRECORD=${OPZCDRECORD//-eject/}
  OPZCDRDAO=${OPZCDRDAO//--eject/} # redundant!
fi

if [ ! -z "$UNOAUNO" ]; then
  WRITER=$CDRECORD
fi

if [ ! -z "$EJECT_CD" ] && [ ! -z "$ALVOLO" ]; then
  # Display a message about something happened some rows before...
  lechoc GREEN  "WARNING:"
  lechoc GREEN  "--eject can't be used with --on-the-fly!"
  lechoc GREEN  "Ignoring --eject"
fi

if [ ! -z "$WRITER" ] && [ "$WRITER" = "$CDRDAO" ] && [ -z "$TOCFILE" ]; then
  TOCFILE="cd_$$.toc"
  lechoc GREEN  "WARNING:"
  lechoc GREEN  "No tocfile specified. Using tocfile %s" "$TOCFILE"
fi

if [ -z "$WRITER" ]; then
  if [ ! -z $NODUMMY ] || [ ! -z $DELFILES ]; then
    lechoc GREEN  "WARNING:"
    lechoc GREEN  "-r and -d options have no effect without -w!"
  fi
else
  if [ "$WRITER" = "$CDRECORD" ]; then
    for t in $T_SUPP; do
      case $t in
        wav|cdr|au) #nope...
          ;;
        *)
          lechoc STDERR "cdrecord only recognize wav, cdr, or au file format"
          USCITA=$ERR_BAD_CDRTYPE; exit $USCITA
          ;;
      esac
    done
  else
    for t in $T_SUPP; do
      case $t in
        wav|cdr) #nope...
          ;;
        *)
          lechoc STDERR "cdrdao only recognize wav or cdr file format"
          USCITA=$ERR_BAD_CDRTYPE; exit $USCITA
          ;;
      esac
    done
  fi
  if [ -z "$SOX" ]; then
    lechoc GREEN  "WARNING:"
    lechoc GREEN  "Without sox you must be sure that all songs are encoded in 44100Hz"
    lechoc GREEN  "rate and with properly byte-encodings to write on a CD!"
  fi
fi

# Plugins sanity checks...
for PLUG in $PLUGINS_WITH_PARAMETERS; do
  USCITA=0
  sanity_check_$PLUG 2>/dev/null
  if [ $USCITA -ne 0 ]; then
    lechoc STDERR "%s: %s" "$PLUG" "$STRERROR"
    exit $[ USCITA + 10000 ]
  fi
done

if [ ! -z $TOCFILE ]; then
  echo "CD_DA" >> $TOCFILE
  echo "" >> $TOCFILE
fi

# Check if all files are readable:
lechoc CYAN  "Phase 1: checking file type..."
for PLUG in ${PHASE1_BEGIN[@]}; do
  begin_$PLUG
  EXIT_PLUG=$?
  if [ $EXIT_PLUG -ne 0 ]; then
    lechoc STDERR "%s: %s" "$PLUG" "$STRERR"
    exit $EXIT_PLUG
  fi
done
c=0
while read i; do
  echoc CYAN "--------------------------------------------------------------"
  if [ -r "$i" ]; then
    if [ -z "$TRUST_EXT" ]; then
      TIPOFILE="$(file -Lb "$i")"
    else
      TIPOFILE=
    fi
    tempf=$(echo "$i"|tr A-Z a-z)
    #found=0
    ISTYPE=
    for PLUG in $AUDIO_PLUGINS; do
      check_file_type_$PLUG
      if [ ! -z "$ISTYPE" ]; then
        #found=1
        break
      fi
    done
    #if [ $found -eq 0 ]; then
    if [ -z "$ISTYPE" ]; then
      lechoc GREEN  "WARNING: File %s is not a valid audio file." "$i"
      continue;
    fi
    echo "$i">>"$FILETEMPSONG"
    estrai_tempo "$i" "$ISTYPE"
    TIME[$c]="$TEMPOSONG"
    # To insert complete path for file:
    # There is some other way to do this quiclky?
    SONG_NAME="$(basename "$i")"
    cd "$(dirname "$i")"
    #SONG_DIR="$(pwd -L)"
    SONG_DIR="$PWD"
    cd -
    SONG[$c]="$SONG_DIR/$SONG_NAME"
    TRACK=$[ c + 1 ]
    TYPE[$c]="$ISTYPE"
    extract_check_info_$ISTYPE
    RATE[$c]="$RET_RATE"
    KBITSTEREO="$RET_KBITSTEREO"
    [ ! -z $RET_MONO ] && CHANNEL[$c]=$RET_MONO || CHANNEL[$c]=2
    lechoc CYAN  "Track : %.2d" "$TRACK"
    lechoc CYAN  "File  : %s" "$(basename "$tempf" .$ISTYPE).$ISTYPE"
    lechoc CYAN  "Type  : %s" "$FILETYPE"
    lechoc CYAN  "Rate  : %s Hz (%s)" "${RATE[$c]}" "$KBITSTEREO"
    lechoc CYAN  "Time  : %s" "$TEMPOSONG"
    c=$[ c + 1 ]
  else
    lechoc GREEN  "WARNING: File %s is not readable" "$i"
  fi
done <$SONGFILE
echoc CYAN "--------------------------------------------------------------"
lechoc CYAN  "Check finished."

if [ ${#SONG[@]} -eq 0 ]; then
  lechoc STDERR  "No valid song! What kind of playlist you've submitted?" 
  USCITA=$ERR_NO_VALID_SONG; exit $USCITA
fi

for PLUG in ${PHASE1_END[@]}; do
  end_$PLUG
  EXIT_PLUG=$?
  if [ $EXIT_PLUG -ne 0 ]; then
    lechoc STDERR "%s: %s" "$PLUG" "$STRERR"
    exit $EXIT_PLUG
  fi
done

(
echo
lechoc CYAN  "Phase 2: checking time"
for PLUG in ${PHASE2_BEGIN[@]}; do
  begin_$PLUG
  EXIT_PLUG=$?
  if [ $EXIT_PLUG -ne 0 ]; then
    lechoc STDERR "%s: %s" "$PLUG" "$STRERR"
    exit $EXIT_PLUG
  fi
done

calcola_tempo
TEMPO=$(printf "%0.2d:%0.2d/%0.2d" $TOTMIN $TOTSEC $TOTMSEC)
lechoc CYAN  "Total time for %s songs: %s" "${#SONG[@]}" "$TEMPO"

for PLUG in ${PHASE2_END[@]}; do
  end_$PLUG
  EXIT_PLUG=$?
  if [ $EXIT_PLUG -ne 0 ]; then
    lechoc STDERR "%s: %s" "$PLUG" "$STRERR"
    exit $EXIT_PLUG
  fi
done
)
EXIT_SS=$?
if [ $EXIT_SS -ne 0 ]; then
  exit $EXIT_SS
fi

if [ ! -z $ONLYTIME ]; then
  USCITA=0; exit $USCITA
fi

(
echo
lechoc CYAN  "Phase 3: Decode"
> $WROTEFILES
WROTE=
for PLUG in ${PHASE3_BEGIN[@]}; do
  begin_$PLUG
  EXIT_PLUG=$?
  if [ $EXIT_PLUG -ne 0 ]; then
    lechoc STDERR "%s: %s" "$PLUG" "$STRERR"
    exit $EXIT_PLUG
  fi
done
numero=1
nc=0
for i in "${SONG[@]}"; do 

  tempname="$(echo "$i"|tr A-Z a-z)"
  nome=${tempname/%.${TYPE[$nc]}/}
  numbered_name $numero "$nome"

  setup_vars_${TYPE[$nc]}

  [ -z "$TOCFILE" ] || echo "TRACK AUDIO" >> $TOCFILE

  echo ""
  lechoc CYAN  "Decoding %s ..." "$nomef"

  if [ ! -z $SOX ]; then
    if [ ${RATE[$nc]} -lt 44100 ]; then
      lechoc CYAN  "Automatic conversion: %sHz -> 44100Hz with sox" \
                   "${RATE[$nc]}"
      if [ ! -z "$ALVOLO" ]; then
        to_stdout_buffered_${TYPE[$nc]} "$i" | sox_convert_rate_piped | \
          writecd "$CDRECORD" "" "$OPZCDRECORD -nofix -waiti" "-"
      else
        to_stdout_buffered_${TYPE[$nc]} "$i" | sox_convert_rate_file
      fi
    elif [ ! -z "$(eval echo \$${TYPE[$nc]}_OUT_TYPE)" ]; then
      lechoc CYAN  "Automatic conversion: %s -> %s with sox" "${TYPE[$nc]}" \
                   "$(eval echo \$${TYPE[$nc]}_OUT_TYPE)"
      if [ ! -z "$ALVOLO" ]; then
        to_stdout_buffered_${TYPE[$nc]} "$i" | sox_convert_format_piped | \
          writecd "$CDRECORD" "" "$OPZCDRECORD -nofix -waiti" "-"
      else
        to_stdout_buffered_${TYPE[$nc]} "$i" | sox_convert_format_file
      fi
    elif [ ${CHANNEL[$nc]} -ne 2 ]; then
      lechoc CYAN  "Automatic channel conversion: %s -> 2" "${CHANNEL[$nc]}"
      if [ ! -z "$ALVOLO" ]; then
        to_stdout_buffered_${TYPE[$nc]} "$i" | sox_convert_channel_piped | \
          writecd "$CDRECORD" "" "$OPZCDRECORD -nofix -waiti" "-"
      else
        to_stdout_buffered_${TYPE[$nc]} "$i" | sox_convert_channel_file
      fi
    else 
      if [ ! -z "$ALVOLO" ]; then
        to_stdout_no_buffer_${TYPE[$nc]} "$i" | \
          writecd "$CDRECORD" "" "$OPZCDRECORD -nofix -waiti" "-"
      else
        decode_${TYPE[$nc]} "$i"
      fi
    fi
  fi
  echo ""

  if [ -z "$ALVOLO" ]; then
    if [ -r "$OUTPUT_FILE" ]; then
      WROTE="$WROTE $OUTPUT_FILE"
      echo "$OUTPUT_FILE">>$WROTEFILES
    else
      lechoc STDERR  "There is some problem with %s" "$OUTPUT_FILE"
      lechoc STDERR  "Process aborted."
      USCITA=$ERR_NOEXIST; exit $USCITA
    fi
  fi
  
  if [ ! -z "$UNOAUNO" ]; then
    lechoc CYAN -n  "Writing this track"
    if [ -z "$NODUMMY" ]; then
      OPZDUMMY="-dummy"
      lechoc CYAN -n  " in dummy mode"
    fi
    lechoc CYAN "..."
    writecd "$CDRECORD" "$OPZDUMMY" "$OPZCDRECORD -nofix" "$OUTPUT_FILE"
    if [ ! -z "$DELFILES" ]; then
      lechoc CYAN  "Removing %s" "$OUTPUT_FILE"
      rm -f "$OUTPUT_FILE" 
    fi
    > $WROTEFILES
    WROTE=""
  fi
  
  if [ ! -z "$TOCFILE" ]; then 
    echo "AUDIOFILE \"$OUTPUT_FILE\" 0">>$TOCFILE
    echo "" >>$TOCFILE
  fi

  numero=$[ numero + 1 ]
  nc=$[ nc + 1 ]
done

echo ""
if [ ! -z "$UNOAUNO" ] || [ ! -z "$ALVOLO" ]; then
  echoc CYAN -n "Fixating TOC... "
  writecd "$CDRECORD $EJECT_CD" "" "-v -fix" 
  echoc CYAN "Done"
  USCITA=0; exit $USCITA
fi

echo

for PLUG in ${PHASE3_END[@]}; do
  end_$PLUG
  EXIT_PLUG=$?
  if [ $EXIT_PLUG -ne 0 ]; then
    lechoc STDERR "%s: %s" "$PLUG" "$STRERR"
    exit $EXIT_PLUG
  fi
done

)
EXIT_SS=$?
if [ $EXIT_SS -ne 0 ]; then
  exit $EXIT_SS
fi

if [ ! -z "$UNOAUNO" ] || [ ! -z "$ALVOLO" ] || [ -z "$WRITER" ]; then
  USCITA=0; exit $USCITA
fi

(
WROTE=
while read l; do
  WROTE="$WROTE $l"
done <$WROTEFILES

lechoc CYAN  "Phase 4: burning"
for PLUG in ${PHASE4_BEGIN[@]}; do
  begin_$PLUG
  EXIT_PLUG=$?
  if [ $EXIT_PLUG -ne 0 ]; then
    lechoc STDERR "%s: %s" "$PLUG" "$STRERR"
    exit $EXIT_PLUG
  fi
done

(
  [ "$WRITER" = "$CDRECORD" ] && TXT="cdrecord" || TXT="cdrdao"
  lechoc CYAN  "Writing procedure with %s" "$TXT"
)

if [ -z "$NODUMMY" ]; then
  quest  "Do you want to test this burning process (dummy write)?" $"Dummy write..." $"Will not perform dummy write..." 1
  if [ $? -eq 1 ]; then
    [ "$WRITER" = "$CDRECORD" ] && OPZDUMMY="--dummy" || OPZDUMMY="--simulate"
  fi
else 
  lechoc CYAN -n  "Insert a blank CD-R in mastering device and press ENTER "
  read PAUSE
fi

if [ "$WRITER" = "$CDRECORD" ]; then
  #writecd "$WRITER" "$OPZDUMMY" "$OPZCDRECORD" "$WROTE"
  OPZWRITER="$OPZCDRECORD"
  WHAT_TO_WRITE="$WROTE"
  #if [ $? -ne 0 ]; then
  #  exit $ERR_BAD_WRITE
  #fi
else
  $WRITER show-toc $TOCFILE 2>$TMPTOC
  $GREP -q "ERROR" $TMPTOC>/dev/null
  if [ $? -eq 0 ]; then
    lechoc STDERR  "There is some problem: toc-file has some error..." 
    USCITA=$ERR_TOC_ERR; exit $USCITA
  fi
  #writecd "$WRITER write" "$OPZDUMMY" "$OPZCDRDAO" "$TOCFILE"
  WRITER="$WRITER write"
  OPZWRITER="$OPZCDRDAO"
  WHAT_TO_WRITE="$TOCFILE"
  #if [ $? -ne 0 ]; then
  #  exit $ERR_BAD_WRITE
  #fi
fi

writecd "$WRITER" "$OPZDUMMY" "$OPZWRITER" "$WHAT_TO_WRITE"
if [ $? -ne 0 ]; then
  exit $ERR_BAD_WRITE
fi

if [ ! -z $DELFILES ]; then
  lechoc CYAN  "Removing files..."
  rm -fv $WROTE
fi
for PLUG in ${PHASE4_END[@]}; do
  end_$PLUG
  EXIT_PLUG=$?
  if [ $EXIT_PLUG -ne 0 ]; then
    lechoc STDERR "%s: %s" "$PLUG" "$STRERR"
    exit $EXIT_PLUG
  fi
done
)
EXIT_SS=$?
if [ $EXIT_SS -ne 0 ]; then
  exit $EXIT_SS
fi

