#! /bin/bash -eu
# Last edited on 2026-07-05 05:11:40 by stolfi

# Reads a list of {k}-repeats for various {k} and a text file where
# those repeats were found. Plots each repeat as a function of its
# position in the file.
#
# Command line arguments are a name {plot_name} for the plot image, a
# title {plot_title} for the same, and the name {ex_name} of the file
# with the repeated patterns. All file names should be given without
# folder part (assumed "res") or extension.
#
# The {k}-repeats file "res/${ex_name}.rex" must have one entry per line
# with a "@" or "|" on column 1, followed by three skipped fields
# and then the text of the repeat.
# 

plot_name="$1"; shift    # Name (sans folder and extension) of output plot file.
plot_title="$1"; shift   # Title for plot as a whole.
horz_title="$1"; shift   # Title for horizontal axis
ex_name="$1"; shift      # Name (sans folder and extension) of input repeats file.

echo "$0: ex_name = '${ex_name}' " 1>&2

temp="/tmp/$$"

ex_file="res/${ex_name}.rex"

# # Find the max lenght {kmax} of any repeat:
# kmax=$(
#   cat ${ex_file} \
#     | gawk ' BEGIN { kmax=0} /^ *[0-9]/{ k=$5; if (k>kmax) { kmax=k }} END{ print kmax } ' \
# )
kmax=10
echo "kmax = ${kmax}" 1>&2

export GDFONTPATH=ttf

colors=( $( ./make_some_colors.sh ${kmax} ) ) 

temp_plot="${temp}-big.png"
echo "creating plot ..." 1>&2 
gnuplot <<EOF

big_hsize = 2400
big_vsize = 800

set term pngcairo size (big_hsize),(big_vsize) font "arial,20" noenhanced
set output "${temp_plot}"

set xrange [-9.5:375.5]
set xtics 20
set mxtics 4

set yrange [-0.5:(${kmax} + 1.5)]
set ytics 1

set xzeroaxis
set grid ytics
set grid xtics
set xlabel "${horz_title}"
set ylabel "Repeat size k"

set title "${plot_title}"

plot \
  "${ex_file}" using 2:5 notitle with points pt 7 ps 1.0 lc rgb '#ff2200'

quit
EOF

echo "rescaling plot ..." 1>&2 
if [[ -s ${temp_plot} ]]; then
  good_plot="res/${plot_name}-rep-hist.png"
  convert ${temp_plot} -resize '50%' ${good_plot}
  display ${good_plot}
  rm -f ${temp}-[a-z][a-z]* ${temp}.[a-z][a-z][a-z]
else
  echo "** ${temp_plot} not generated" 1>&2; exit 1
fi
