#! /bin/bash
# Last edited on 2022-05-02 05:50:28 by stolfi

# Plots the frequencies of names in two files.

# Input is a file "${name}.txt" has triplets "{NAME} {COUNTX} {COUNTY}" on each line.
# Assumes names have no embedded spaces.
# Ignores '#' comments, blank lines, {NAME}="anonymous".
# Output plot is "${name}.png"

title="$1"; shift   # Plot title.
xtitle="$1"; shift  # X axis title.
ytitle="$1"; shift  # Yaxis title.
name="$1"; shift    # File name minus extension.

tmp="/tmp/$$" 

dfile="${name}.txt" # Input data file.
pfile="${name}.png" # Final plot file.

tpfile="${tmp}.png"  # Temporary plot file.

# Get largest fregs:
fmaxs=( `gawk '//{ cu=$2; cs=$3; if(cu>u){u=cu} if(cs>s){s=cs}  } END { print u, s }' ${dfile} ` )
echo "fmaxs = ${fmaxs[*]}" 1>&2
xmax=${fmaxs[0]}    # X scaling count.
ymax=${fmaxs[1]}    # Y scaling count.

export GDFONTPATH=.:..

gnuplot <<EOF
set term png size 1000,1000 font "arial,24"
set output "${tpfile}"

set title "${title}"
set xlabel "${xtitle} (millions)"
set ylabel "${ytitle}"

xpmax = 1.05 * ${xmax}
ypmax = 1.05 * ${ymax}

set xrange [-0.2:xpmax/1000000.0]
set yrange [-2:ypmax]

xv(k) = column(k)/1000000.0
yv(k) = column(k)
rv(k) = column(k)*ypmax/xpmax

plot \
  "${dfile}" using (xv(2)):(yv(3)) notitle with points pt 7 ps 1 lc rgb '#880000', \
  ""         using (xv(2)):(rv(2)) notitle with lines lc rgb '#008800'
quit
EOF

if [[ -s ${tpfile} ]]; then
  convert ${tpfile} -resize '50%' ${pfile}
  display ${pfile}
else
  echo "** plot failed" 1>&2
fi
rm -f ${tmp}.*
