#!/bin/bash
#####################################################################
# filename:	getWxRpt
#
# description:	Uses festival text-to-speech synthesiser to convert 
#		weather data to audio and save as a ul file.
#
# usage:	getWxRpt
#
# history:
# 2004/08/18	kc6hur	Original Release
#
# Modified by w0anm
# $Id: getWxRpt 46 2009-04-10 04:27:25Z  $
######################################################################
LOGFILE=/tmp/wx1.txt
# Load config file

if [ -f ${CUSTOM}/wx_scripts.conf ] ; then
    source ${CUSTOM}/wx_scripts.conf
else
    echo "Missing ${CUSTOM}/wx_scripts.conf file, aborting..."
    exit 1
fi

# if ICAO_STN not an argument, then use what is defined in configure file.
if [ "$1" = "" ] ; then
    ICAO_LIST=$ICAO_STN
else
    ICAO_LIST=$1
fi

# WXTXT="$WXDIR/report/$ICAO.txt"
# WXTXT_TMP="/tmp/$ICAO.txt"
# WXAUD="$WXDIR/report/$ICAO.ul"
# WXURL="http://weather.noaa.gov/pub/data/observations/metar/stations/$ICAO.TXT"

if [ ! -d $WXDIR/report ] ; then
    mkdir -p $WXDIR/report
fi


#-----------------------------------------------------------------------
# Get the METAR weather string and convert it to a text file.

for ICAO in $ICAO_LIST ; do
    log "Get METAR for $ICAO"
    WXTXT="$WXDIR/report/$ICAO.txt"
    WXTXT_TMP="/tmp/$ICAO.txt"
    WXAUD="$WXDIR/report/$ICAO"
    
WXURL="http://tgftp.nws.noaa.gov/data/observations/metar/stations/$ICAO.TXT"

   ## rm -f $WXTXT &>/dev/null

   /usr/bin/wget -q -O - $WXURL > /tmp/wx_metar

   if `/usr/bin/wget -q -O - $WXURL | /metar2text > $WXTXT 2>> $LOGFILE` ; then 
      log "Error getting METAR for $ICAO"
      exit 0
   else
      log "Got METAR for $ICAO"
   fi
   # Fix any formating issues:
   sed -f  /wxtext_conv.sed $WXTXT >  $WXTXT_TMP
#   echo  "end of report. . . " >> $WXTXT_TMP
   cp $WXTXT_TMP $WXTXT

   # Convert text output into a ul file.
   #
   if [ -f $WXTXT ] ; then
      if [ $TEXT2SPEECH = "festival" ] ; then
        #$TEXT2WAVE -F 48000 -otype wav -o $WXAUD1.wav $WXTXT
      	#ffmpeg -i $WXAUD.wav -y -ar 48000 $WXAUD1.wav
	pico2wave -w $WXAUD.wav "$(cat $WXTXT)"
	sox --norm -V -v 0.1 $WXAUD.wav -r 48000 $WXAUD1.wav
        /usr/local/bin/wav2dvtool $WXAUD1.wav KD8TUZ_REPORT KD8TUZ_B KD8TUZ_G "Hamilton WX Report" $WXAUD.dvtool
        
	# sourced out audio files
	#echo "$WXTXT"
	#espeak $WXTXT $WXAUD
      fi
      if [ $TEXT2SPEECH = "cepstral" ] ; then
          $TEXT2WAVE -m text -f $WXTXT -p audio/encoding=ulaw,audio/sampling-rate=8000,audio/volume=$SWIFT_VOL -o $WXAUD.new 
      fi
      #mv $WXTXT_TMP $WXTXT
      #log "$WXAUD has been saved"
      #rm -f $WXTXT &>/dev/null
   fi
done
exit 0
