#
# 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
#
#
# Functions for sox:
# FORMAT FILE: wav au

# Due to its fundamental importance you must think this plugin like a 
# MODULE and not a plugin.

plugin_present_sox () {
  return 0
}

parse_param_t_sox () {
  SOX_TOFMT="$1"
  T_SUPP="$T_SUPP $SOX_TOFMT"
  return 0
}

format_error () {
  lechoc STDERR "There is an error in time extracting. Perhaps this is not a"
  lechoc STDERR "valid $1 file. Related infos:"
  lechoc STDERR "FILENAME	: %s" "$2"
  lechoc STDERR "TIPOFILE	: %s" "$TIPOFILE"
  lechoc STDERR "FILETYPE	: %s" "$FILETYPE"
  USCITA=$ERR_NO_SUPP_TYPE; exit $USCITA
}
    
extract_time_wav () {
  if [ -z "$SOX" ]; then
    local b=176400
    local t=$(ls -l -d -G "$1"  |tr -s ' '|cut -d' ' -f4) # filesize
  else
    local TMP=$($SOX -V -t wav "$1" -t ossdsp /dev/null 2>&1 |$GREP "byte/sec" \
                |cut -d':' -f2 |cut -d',' -f1,4|tr -s ' '|cut -d' ' -f2,4)
    local b=$(echo $TMP|cut -d' ' -f1)
    local t=$(echo $TMP|cut -d' ' -f2)
  fi

  local tm=$(expr "$t" / "$b" 2>/dev/null)
  if [ -z "$tm" ] || [ $(expr "$tm" : ".*/.*") -eq ${#tm} ]; then
    format_error wav "$1"
  fi

  if [ "$(expr $tm / 60)" -gt 99 ]; then
    RET_WCL=1
    TS="00:00:00"
  else
    local rtm=$(expr $t % $b)
    TS=$(printf "%0.2d:%0.2d.%0.2d" "$(expr $tm / 60)" \
                "$(expr $tm % 60)" "$(expr $(expr $rtm \* 100) / $b)")
    RET_WCL=0
  fi
}

extract_time_au () {
  #local hexstr=$(cat $fn|cut -b19,20|hexdump -n 2|head -n 1| \
  #               cut -d' ' -f2|tr a-f A-F)
  #local hexnum="${hexstr:2:2}${hexstr:0:2}"
  #local samples=$(echo "ibase=16; $hexnum"|bc)
  if [ -z "$SOX" ]; then
    samples=$(file "$1" |cut -d',' -f 3|cut -d' ' -f2)
  else
    local TMP=$($SOX -V -t au "$1" -t ossdsp /dev/null 2>&1 |\
                $GREP "sample rate" |cut -d':' -f3);
    local TMP2=${TMP%%[0-9]*[0-9]}
    local samples=${TMP:${#TMP2}}
  fi
  local t=$(ls -l -d -G "$1"  |tr -s ' '|cut -d' ' -f4) # filesize
  local tm=$(expr "$t" / "$samples")
  if [ -z "$tm" ] || [ $(expr "$tm" : ".*/.*") -eq ${#tm} ]; then
    format_error au "$1"
  fi

  if [ "$(expr $tm / 60)" -gt 99 ]; then
    RET_WCL=1
    TS="00:00:00"
  else
    local rtm=$(expr $t % $samples)
    TS=$(printf "%0.2d:%0.2d.%0.2d" "$(expr $tm / 60)" \
                "$(expr $tm % 60)" "$(expr $(expr $rtm \* 100) / $samples)")
    RET_WCL=0
  fi
}

extract_time_cdr () {
  local b=176400
  local t=$(ls -l -d -G "$1"  |tr -s ' '|cut -d' ' -f4) # filesize
  local tm=$(expr "$t" / "$b")
  if [ -z "$tm" ] || [ $(expr "$tm" : ".*/.*") -eq ${#tm} ]; then
    format_error cdr "$1"
  fi

  if [ "$(expr $tm / 60)" -gt 99 ]; then
    RET_WCL=1
    TS="00:00:00"
  else
    local rtm=$(expr $t % $b)
    TS=$(printf "%0.2d:%0.2d.%0.2d" "$(expr $tm / 60)" \
                "$(expr $tm % 60)" "$(expr $(expr $rtm \* 100) / $b)")
    RET_WCL=0
 fi
}

extract_check_info_wav () {
  if [ ! -z "$TRUST_EXT" ]; then
    $SOX -V -t wav "$i" -t ossdsp /dev/null >$SONGDATA 2>&1 
    RET_RATE=$(cat $SONGDATA|grep "samp/sec"|cut -d',' -f3|cut -d' ' -f2)
    RET_KBITSTEREO=$(cat $SONGDATA|grep "byte/sec"|cut -d':' -f2|\
                     cut -d',' -f1|tr -s ' ')
    return
  fi
  RET_RATE=$(echo "$TIPOFILE"|cut -d',' -f5|cut -d' ' -f3)
  if [ -z "$RET_RATE" ]; then
    RET_RATE=$(echo "$TIPOFILE"|cut -d',' -f3|cut -d' ' -f3)
    RET_KBITSTEREO=$(echo "$TIPOFILE"|cut -d',' -f3|cut -d' ' -f2)
  else
    RET_KBITSTEREO=$(echo "$TIPOFILE"|cut -d',' -f4,5|cut -d' ' -f2,3,4)
  fi
}

extract_check_info_au () {
  if [ ! -z "$TRUST_EXT" ]; then
    $SOX -V -t au "$i" -t ossdsp /dev/null >$SONGDATA 2>&1 
    RET_RATE=$(cat $SONGDATA | grep "using sample rate"|\
               cut -d':' -f3|cut -d' ' -f5)
    RET_KBITSTEREO=$(cat $SONGDATA | grep "encoding"|tr -s ' ')
    return
  fi
  RET_RATE=$(echo "$TIPOFILE"|cut -d',' -f3|cut -d' ' -f2)
  RET_KBITSTEREO=$(echo "$TIPOFILE"|cut -d':' -f2|cut -d',' -f1)
}

extract_check_info_cdr () {
  RET_RATE="44100"
  if [ ! -z "$TRUST_EXT" ]; then
    local add=""
  else
    local add=",$(echo $TIPOFILE|cut -d',' -f2))"
  fi
  RET_KBITSTEREO="128Kbit/s $add"
}

check_file_type_sox () {
  if [ ! -z "$TRUST_EXT" ]; then
    if [ "$(basename "$tempf" .wav)" != "$(basename "$tempf")" ]; then
      ISTYPE="wav"
      FILETYPE="WAVE audio"
    elif [ "$(basename "$tempf" .au)" != "$(basename "$tempf")" ]; then
      ISTYPE="au"
      FILETYPE="Sun/NeXT audio data"
    elif [ "$(basename "$tempf" .cdr)" != "$(basename "$tempf")" ]; then
      ISTYPE="cdr"
      FILETYPE="raw audio data"
    fi
    if [ ! -z "$ISTYPE" -a -z "$WRITER" ]; then
      lechoc GREEN $"WARNING: $ISTYPE files ignored without -w option!"
      ISTYPE=
      FILETYPE=
    fi
  else
    if [ "${TIPOFILE:$WAVS1:$WAVS2}" = "$WAVCRITERIA" ]; then
      if [ -z "$WRITER" ]; then
        lechoc GREEN $"WARNING: WAV files ignored without -w option!"
      else
        ISTYPE="wav"
        FILETYPE="$(echo $TIPOFILE|cut -d',' -f2)"
      fi
    elif [ ! -z "$AUCRITERIA" ] && [ "${TIPOFILE:$AUS1:$AUS2}" = "$AUCRITERIA" ]; then
      if [ -z "$WRITER" ]; then
        lechoc GREEN $"WARNING: AU files ignored without -w option!"
      else
        ISTYPE="au"
        FILETYPE="$(echo $TIPOFILE|cut -d':' -f1)"
      fi
    elif [ ! -z "$CDRCRITERIA" ] && [ "${TIPOFILE:$CDRS1:$CDRS2}" = "$CDRCRITERIA" ]; then
      if [ -z "$WRITER" ]; then
        lechoc GREEN $"WARNING: CDR files ignored without -w option!"
      else
        ISTYPE="cdr"
        FILETYPE="$(echo $TIPOFILE|cut -d',' -f1)"
      fi
    elif [ "$(basename "$tempf" .cdr)" != "$(basename "$tempf")" ]; then
      if [ -z "$WRITER" ]; then
        lechoc GREEN $"WARNING: CDR files ignored without -w option!"
      else
        lechoc GREEN "WARNING: Can't find cdr signature in this file!"
        lechoc GREEN "I will beleave only to file extension"
        ISTYPE="cdr"
        FILETYPE="raw audio data"
      fi
    fi
  fi
}

common_vars () {
  FLYFMT="$1"
  SOX_OUT_TYPE="$SOX_TOFMT"
  OUTPUT_FILE="$SPOOLDIR/$nomef.$SOX_TOFMT"
}

setup_vars_wav () {
  common_vars "wav"
}

setup_vars_au () {
  common_vars "au"
}

setup_vars_cdr () {
  common_vars "cdr"
}

to_stdout_buffered_wav () {
  to_stdout_no_buffer_wav
}

to_stdout_no_buffer_wav () {
  cat "$i"
}

decode_wav () {
  if [ "$SOX_TOFMT" = "${TYPE[$nc]}" ]; then
    ln -sf "$i" "$OUTPUT_FILE"
    #"$nomef.$SOX_TOFMT" 
  else
    to_stdout_no_buffer_wav|sox_convert_format_file
  fi
}

to_stdout_buffered_au () {
  to_stdout_no_buffer_wav 
}

to_stdout_no_buffer_au () {
  to_stdout_no_buffer_wav 
}

decode_au () {
  decode_wav
}

to_stdout_buffered_cdr () {
  to_stdout_no_buffer_wav 
}

to_stdout_no_buffer_cdr () {
  to_stdout_no_buffer_wav 
}

decode_cdr () {
  decode_wav 
}

setup_cmdsoxfly () {
  if [ "$(echo $FLYFMT|tr a-z A-Z)" = "RAW" ]; then
    CMDSOXFLY="$SOX -t raw -r ${RATE[$nc]} -s -w -c ${CHANNEL[$nc]}"
  else
    CMDSOXFLY="$SOX -t $FLYFMT"
  fi
}

sox_convert_rate_piped () {
  setup_cmdsoxfly
  $CMDSOXFLY - -t wav -c 2 -r 44100 -s -w - rate
}

sox_convert_rate_file () {
  setup_cmdsoxfly
  $CMDSOXFLY - -c 2 -r 44100 -s -w "$OUTPUT_FILE" rate
}

sox_convert_channel_piped () {
  setup_cmdsoxfly
  $CMDSOXFLY - -t wav -c 2 -s -w - 
}

sox_convert_channel_file () {
  setup_cmdsoxfly
  $CMDSOXFLY - -c 2 -s -w "$OUTPUT_FILE" 
}


sox_convert_format_piped () {
  setup_cmdsoxfly
  $CMDSOXFLY - -t wav -c ${CHANNEL[$nc]} -s -w -c 2 - 
}

sox_convert_format_file () {
  setup_cmdsoxfly
  $CMDSOXFLY - -c 2 -s -w "$OUTPUT_FILE"
}

