#! /bin/bash
# Last edited on 2021-03-30 03:43:18 by jstolfi

# Reads a power spectrum file as produced by {curve_spectrum}.
# Generates a plot of it.

cmd="$0"; cmd="${cmd##*/}"

dfile="$1"; shift    # Name of file with spectrum data.
oprefix="$1"; shift  # Prefix for output file names, with dir.
show=$1; shift       # Display plot if 1, silent if 0

# END COMMAND LINE PARSING
# ----------------------------------------------------------------------

export PATH=".:..:../..:${PATH}"

# Prefix for temporary file names
tmp="/tmp/$$"

hPix=1800
vPix=800

tfile="${tmp}.png"
export GDFONTPATH="tt-fonts"

for ia in 0 1 ; do

  if [[ ${ia} -eq 0 ]]; then axname="X"; else axname="Y"; fi

  for mag in 0 1 ; do
   
    # Plot the spectrum of coordinate {ia}.
    # If {mag} is 1, plot enlarged version of low frequencies.
    
    if [[ ${mag} -ne 0 ]]; then
      xmin="-5"; xmax="40" 
    else 
      xmin="-100"; xmax=""
    fi

    gnuplot <<EOF
      set terminal png truecolor size ${hPix},${vPix} font "arial,18"
      set output "${tfile}"

      set xlabel "${xlabel}"
      set ylabel "${ylabel}"

      set xrange[${xmin}:${xmax}]
      set yrange[1.0e-5:]
      
      set logscale y
      
      set grid ytics lt 1 lw 2 lc rgb '#cccccc'

      mag = ${mag}
      ia = ${ia}
      icol = 2 + ia
      
      lwd = 1 + 4*mag
      psz = 0.5 + 3*mag

      plot \
        "${dfile}" using 1:(column(icol)) notitle           with impulses lt 1 lw (lwd) lc rgb '#dd2200', \
        ""         using 1:(column(icol)) title "${axname}" with points   pt 7 ps (psz) lc rgb '#dd2200'

EOF

    if [[ -s ${tfile} ]]; then
      pfile="${oprefix}-rms-${axname}-mag${mag}.png"
      convert ${tfile} -resize '50%' ${pfile}
      if [[ ${show} -ne 0 ]]; then display ${pfile}; fi
      rm ${tfile}
    else
      echo "** plot failed" 1>&2 ; exit 1
    fi
  done
  
done
