#!/bin/sh
#
# vim:sw=2 ts=8:et sta:fdm=marker
#
#
# Copyright (c) 2009 Ariff Abdullah <ariff@FreeBSD.org>
# All rights reserved.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions
# are met:
# 1. Redistributions of source code must retain the above copyright
#    notice, this list of conditions and the following disclaimer.
# 2. Redistributions in binary form must reproduce the above copyright
#    notice, this list of conditions and the following disclaimer in the
#    documentation and/or other materials provided with the distribution.
#
# THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
# OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
# HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
# LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
# OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
# SUCH DAMAGE.
#
#        $MyBSD$
#
# Date: Wed May 27 15:22:06 MYT 2009
#   OS: FreeBSD miki.MyBSD.org.my 8.0-CURRENT i386
#

z=${1:-zresampler}
bit=${2:-32}
bit=$(($bit / 8))
if [ $bit = 2 ]; then
  maxdb=${3:-110}
else
  maxdb=${3:-180}
fi
width=${4:-45}
height=${5:-500}
dir=${6:-down}
if [ "$dir" = "up" ]; then
  src=44100
  dst=96000
elif [ "$dir" = "custom" ]; then
  src=$7
  dst=$8
else
  src=96000
  dst=44100
fi
qmin=`$z -q help 2>&1 | awk '{print $3,$5}' | sed 's/,//g'`
qmax=$qmin

qmin=${qmin%% *}
qmax=${qmax##* }

sinewav="`mktemp -u XXXXXXXX`.wav"

trap "rm -f $sinewav" 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

sox -t null -c 1 -r $src -s -${bit} /dev/null -t wavpcm $sinewav       \
  synth 8 sine create 0+$(($src / 2)) vol -6dB 2> /dev/null

q=$qmin

mkdir -p ./spectrogram

while [ $q -le $qmax ]; do
  f=`printf "%04d" $q`
      $z $sinewav -r $dst -q $q -t wav - |                          \
      sox -t wav - -n spectrogram -o ./spectrogram/tmp_z_q_${f}.png     \
      -c '' -z $maxdb -X $width -Y $height -w k 2> /dev/null
      pngcrush                          \
        ./spectrogram/tmp_z_q_${f}.png  \
        ./spectrogram/z_q_${f}.png > /dev/null 2>&1
      #-t "${z##*/} (q=$q)" -c '' -z $maxdb -x $width -y $height -w k    \
  q=$(($q + 1))
done

rm -f ./spectrogram/tmp_z_q_*.png