#! /bin/bash
# Last edited on 2022-04-14 17:58:20 by stolfi

# Assumes that the input data file contains only the data sets 
# that have been selected for the tests.

datadir="$1"; shift  # Directory with the ".csv" files for plotting.
rawname="$1"; shift  # Name of input data file (without ${datadir}).
pdffile="$1"; shift  # Name of the plot PDF file.
datasets=( "$@" )    # Dataset names.

rawfile="${datadir}/${rawname}"
ls -l ${rawfile}

tmp="/tmp/$$"

pngtemp="${tmp}.png"

# Create a file ${datafile} with the data points (Delta x Rconn) of the curves.
# Each line has "{id} {dataset} {Delta} {Rconn}" where {id} is the curve index from 1 in Table 1.
# Records are sorted by dataset alphabetically and {Delta} numerically.
# A blank line is inserted between different datasets.

datafile="${tmp}-data.txt"
echo "datafile = ${datafile}" 1>&2 
cat ${rawfile} \
  | tr -d '\015' \
  | sort -k1,1 -k2,2g \
  | gawk \
      -v dslist="${datasets[*]}" \
      ' BEGIN {
          Part_prev = "?"; ip = 0;
          nd = split(dslist, datasets)
          split("", ID)  # Maps dataset name to dataset index in Table 1, from 1.
          for (id = 1; id <= nd; id++) { 
            ID[datasets[id]] = id;
            printf "ID[%s] = %d\n", datasets[id], id > "/dev/stderr";
          }
        }
        /[0-9]/ { 
          if (NF != 6) { printf "**BUG 1!\n" > "/dev/stderr"; exit(1) }
          Part = $1; Delta = $2; Trast = $3; Tfab_RP3 = $4; Tfab_Slic3r = $5; Tfab_HF = $6
          if ( (Part != Part_prev) && (Part_prev != "?") ) { printf "\n"; ip++ }
          Tfab_MIN = (Tfab_RP3 < Tfab_Slic3r ? Tfab_RP3 : Tfab_Slic3r)
          if (Tfab_HF == "-") {
            Rconn = -99;
          } else {
            Rconn = (Tfab_HF - Trast)/(Tfab_MIN - Trast)
          }
          if (Part in ID) { 
            printf "%2d %-20s %5.1f %5.3f\n", ID[Part], Part, Delta, Rconn;
          } else {
            printf "dataset %s ignored\n", Part > "/dev/stderr";
          }
          Part_prev = Part
        }
      ' \
  > ${datafile}

# Create a file ${segmfile} with data to plot the labels.
# Two lines for each dataset.
# The first line line has "{ìd} {dataset} 0 {Rlab}" where {id} is the curve index in Table 1, from 1
# and {Rlab} is the {Rconn} value of the position where the curve label should be printed.
# The second line line has "{ìd} {dataset} {Delta0} {Rconn0}" where
# {(Delta0,Rconn0)} is the first data point of the curve.
# There will be one blank line betwen datasets.

segmfile="${tmp}-segm.txt"
echo "segmfile = ${segmfile}" 1>&2 
cat ${datafile} \
  | gawk \
      ' BEGIN { Part_prev = "?"; 
          # Indexed in {0..np-1}, random order.
          split("", P);   # Part names.
          split("", D);   # {Delta}s.
          split("", R);   # {Rconn}s.
          split("", ID);  # {id}s.
          np = 0
        }
        /[0-9]/ { 
          if (NF != 4) { printf "**BUG 1!\n" > "/dev/stderr"; exit(1) }
          id = $1; Part = $2; Delta = $3; Rconn = $4;
          if ((Part != Part_prev) && (Rconn+0 > 0)) {
            ID[np] = id; P[np] = Part; D[np] = Delta; R[np] = Rconn; 
            Part_prev = Part
            np++;
          }
        }
        END {
          printf "np = %d\n", np  > "/dev/stderr"
          # Index-sort entries by vert coordinate {Rconn}:
          split("", ix); # Indices of curves in order of increasing starting {Rconn}.
          for (i = 0; i < np; i++) { ix[i] = i; }
          for (i = 0; i < np; i++) {
            for (j = i+1; j < np; j++) {
              if (R[ix[i]] > R[ix[j]]) { t = ix[i]; ix[i] = ix[j]; ix[j] = t; }
            }
            printf "%3d %2d %8.3f\n", ix[i], ID[ix[i]], R[ix[i]] > "/dev/stderr"
          }
          # Assign label positions:
          split("", S);  # Label positions.
          yrat = 1.12
          ylab = 8.5
          for (i = np-1; i >= 0; i--) {
            S[ix[i]] = ylab
            ylab = ylab/yrat
          }
          for (ip = 0; ip < np; ip++) {
            printf "%2d %-20s %5.1f %5.3f\n", ID[ip], P[ip], 0,     S[ip];
            printf "%2d %-20s %5.1f %5.3f\n", ID[ip], P[ip], D[ip], R[ip];
            printf "\n"
          }
        }
      ' \
  > ${segmfile}

export GDFONTPATH=".:${HOME}/ttf" 
gnuplot <<EOF
# set term pngcairo enhanced truecolor font "arialb,28" size 1200,1400
# set output "${pngtemp}" 

set term pdfcairo enhanced color font "arialb,28" rounded background "#ffffff" size 8.3,9.8
set output "${pdffile}"

unset title

# Number of datasets in the input
nsets = 13

set cbrange [0:(nsets)]
set palette defined ( 0 "#ff0000", 0.200 "#dd5500", 0.400 "#008800", 0.600 "#0077ff", 0.800 "#2200ff", 1.000 "#cc0088" )
unset colorbox
# set key top right  
unset key

# set ytics 100
# set mytics 5

set logscale x
set xrange [0.45:300]; set xlabel "cooling time limit (seconds)"
set xtics (1 0, 2 0, 4 0, 8 0, 16 0, 32 0, 64 0, 128 0, 256 0 )
set grid xtics,mxtics  lt 1 lw 2 lc rgb '#eecc99', lt 1 lw 2 lc rgb '#eecc99'

set logscale y
set yrange [79:950]; set ylabel "relative connection time (%)"
set ytics ( \
  30 0, 40 0, 50 0, 60 0, 70 0, 80 0, 90 0, \
  100 0, 120 0, 140 0, 160 0, 180 0, 200 0, 250 0, 300 0, 400 0, 500 0, 600 0, 700 0, 800 0, 900 0, \
  1000 0, 1200 0, 1400 0, 1600 0, 1800 0, 2000 0, 2500 0, 3000 0, 4000 0, 5000 0, 6000 0, 7000 0, 8000 0, 9000 0 \
)
set grid ytics,mytics  lt 1 lw 2 lc rgb '#eecc99', lt 1 lw 2 lc rgb '#eecc99'

# Convert {Rconn} to percentages:
vmap(k) = (column(k) < 0 ? 0/0 : 100*column(k))

# Position of label from columns {i} and {j} of ${segmfile}:
labx(i) = (column(i) == 0 ? 0.80 : 0/0)
laby(j) = vmap(j)

# Color of curve from column {k} of ${segmfile}:
clr(k) = column(k) - 1

# Endpoint of dotted line from columns {i} and {j} of ${segmfile}:
segx(i) = (column(i) == 0 ? 0.90 : column(i))
segy(j) = vmap(j)

set linetype 1 lw 3 dashtype (10,10)

plot \
  "${segmfile}" using (labx(3)):(laby(4)):1 with labels right, \
  "${segmfile}" using (segx(3)):(segy(4)):(clr(1)) with lines lt 1 palette, \
  "${datafile}" using 3:(vmap(4)) notitle with linespoints pt 7 ps 2.5 lw 6.0 lc rgb '#fefefe', \
  "${datafile}" using 3:(vmap(4)):(clr(1)) notitle with linespoints pt 7 ps 0.8 lw 4 palette
quit
EOF

###  \
###   "${datadir}/plot_data_SCANLINE.csv" using 2:(vmap(3)):4 title "SCN" with points pt 7 ps 4 lw 2 palette, \
###   "${datadir}/plot_data_ALTSCANLINE.csv" using 2:(vmap(3)):4 title "SCA" with points pt 6 ps 4 lw 2 palette, \
###   "${datadir}/plot_data_RP3.csv" using 2:(vmap(3)):4 title "RP3" with points pt 8 ps 4 lw 2 palette, \
###   "${datadir}/plot_data_SLIC3R.csv" using 2:(vmap(3)):4 title "Slic3r" with points pt 9 ps 4 lw 2 palette

if [[ -s ${pngtemp} ]] ; then 
  convert ${pngtemp} -resize '50%' ${pngfile}
  eom ${pngfile}
fi

if [[ -s ${pdffile} ]] ; then 
  evince ${pdffile}
fi

# rm -f ${datafile} ${pngtemp}
