#! /bin/bash
# Last edited on 2017-10-19 22:14:43 by jstolfi

# Plots histogram of blink locations inside a run

# argments: {SHOWOPT} {BFILE}
# where {SHOWOPT} is either "SHOW" or "NOSHOW", 
# {BFILE} is name of file with blink locations (one blink per line).

show="$1"; shift
sid="$1"; shift
bfile="$1"; shift

dir="${bfile%/*}"
echo "dir = ${dir}" 1>&2 
plotfile="${dir}/s${sid}_blinks_hist.png"

tmp="/tmp/$$"

# Run duration and phase transitions in seconds:
trun=7.0  # Total length of runs.
fxini=0.4 # Typical start of fixation phase. 
stini=3.5 # Fixation-to-stimulus transition.
stfin=6.5 # End of stimulus phase.

# Create file for impulses in plot:
printf "%6.2f %6.2f\n" "${fxini}" 1000 > ${tmp}.bip
printf "%6.2f %6.2f\n" "${stini}" 1000 >> ${tmp}.bip
printf "%6.2f %6.2f\n" "${stfin}" 1000 >> ${tmp}.bip

# Build histogram:
cat ${bfile} \
  | gawk \
      -v sid="${sid}" \
      -v trun="${trun}" \
      -v fxini="${fxini}" \
      -v stini="${stini}" \
      -v stfin="${stfin}" \
      ' BEGIN { 
          tstep = 0.2;
          tmin = -0.4;
          tmax = trun+0.4;
          nbins = int((tmax - tmin)/tstep) + 1;
          split("", h); # Histogram of blinks by time.
        } 
        /^[0-9]+[ ]/ { 
          if (NF != 6) { kaboom(); }
          if ($1 != sid) { next; }
          rid = $2;
          nfl = $3;
          kbl = $4;
          tini = $5;
          tfin = $6;
          if ((tfin >= fxini) && (tini <= stfin))
            { tmed = (2*tini + tfin)/3; # Blinks are assymetrical.
              jmed = int((tmed - tmin)/tstep + 0.5);
              if ((jmed >= 0) && (jmed < nbins)) { h[jmed] ++; }
            }
          next;
        }
        // { kaboom(); }
        END {
          for (j = -1; j <= nbins; j++) { printf "%6.2f %8.5f\n", tmin+tstep*(j+0.5), h[j]; }
        }
      ' \
  > ${tmp}.his
  
# Get the maximum histogram value:
hmax=`cat ${tmp}.his | gawk 'BEGIN {mh=1} /^[ ]*[-+]?[0-9]/ { nh = $2 + 0.0; if (nh > mh) { mh = nh; }} END { print mh; }'`

# cat ${tmp}.his 1>&2 
    
export GDFONTPATH=.

gnuplot <<EOF
set term png size 2000,1000 font "arial,20"
set xrange [-0.11:(${trun} + 0.11)]
set yrange [0:(1.1*${hmax})]
set xtics out 1.0
set mxtics 5
set grid xtics lt 1 lw 3 lc rgb '#ffddaa', lt 1 lw 1.5 lc rgb '#ffddaa'
set grid mxtics
set xzeroaxis lt 1 lw 3 lc rgb '#ffddaa'
set output "${tmp}.png"
unset key

plot \
  "${tmp}.his" using 1:2 with histeps lt 1 lc rgb '#0022ff', \
  "${tmp}.bip" using 1:2 with impulses lt 1 lw 2 lc rgb '#ff0000'
quit
EOF

convert ${tmp}.png -resize '50%' ${plotfile}

if [[ "/${show}" == "/SHOW" ]]; then
  display -title '%d/%f' ${plotfile}
fi

rm -fv ${tmp}.*
    
        
