#! /bin/bash
# Last edited on 2023-10-07 08:57:35 by stolfi

IIMFILE="$1"; shift # Input image file.
IPTFILE="$1"; shift # File with coordinates and marks of ref points.
OIMFILE="$1"; shift # Output image file.
OUNIT="$1"; shift   # Pixels per output user unit.

# Takes an input image {IIMFILE} and a file {IPTFILE} with lines "{TAG}
# {X} {Y}", where {X,Y} are pixel column and row indices of a point in
# in {INFILE}, and {TAG} is the name ("P0", "S12", etc.) of that point.
# Creates an image "{OIMGFILE}.jpg" containing a copy of the {IIMFILE}
# image with marks and labels drawn over it.
# 
# The {TAG} must be a string of letters, digits, or "_". The coordinates
# {X} and {Y} may be fractional, but the window will be synced to whole pixels.
# See "00-Notebook.txt" for the format of {MARKS}.
# 
# The feature {X} {Y} coordinates and the coordinates and dimensions in
# {MARKS} are assumed to be in user coordinates. They will be scaled by
# {1/OUNIT} to get the equivalent in pixels.

echo "generating copy of ${IIMFILE} shoing the ref points of ${IPTFILE} ..." 1>&2
echo "output user unit = ${OUNIT}" 1>&2

tag_prev="" # Tag on previous line.
drawCmds=()
for ptlin in `cat ${IPTFILE} | egrep -e '^[A-Za-z][A-Z0-9a-z_]*[ ]' | sort | sed -e 's:[ ]:_:g' -e 's:[ ]*[#].*$::g'` ; do
  ptargs=( `echo "${ptlin}" | sed -e 's:[_]: :g'` )
  tag="${ptargs[0]}"
  xc="${ptargs[1]}"
  yc="${ptargs[2]}"
  mkargs=( ${ptargs[@]:3} )
  
  if [[ "/${tag}" == "/${tag_prev}" ]]; then
    echo "!! duplicate point tag \"${ptlin}\" -- will overwrite ${OUTFILE}" 1>&2
  fi
  tag_prev="${tag}"
  
  # Append a "T" mark at the end of {mkargs?:
  mkargs+=( "T" ${xc} ${yc} ${tag} )
  
  drawCmds+=( \
    ` generate_draw_mark_cmds.gawk \
          -v WSIZE=0 \
          -v WX=0 \
          -v WY=0 \
          -v MKARGS="${mkargs[*]}" \
          -v OUNIT=${OUNIT} \
          -v WSCALE=1 \
          -v TAG="${tag}" \
    ` \
  )

done

# Hack: replace "_" by " " in each element of {drawCmds} without
# splitting it into two elements:
echo "computing the mark drawing commands ..." 1>&2
i=0;
while [[ ${i} -lt ${#drawCmds[@]} ]]; do 
  drawCmds[i]="`echo ${drawCmds[i]} | sed -e 's:[_]: :g'`"
  i=$(( $i + 1 ))
done
# echo "${drawCmds[*]}" | sed -e 's:-draw:@-draw:g' | tr '@' '\012' 1>&2

echo "writing ${OIMFILE} ..." 1>&2

convert ${IIMFILE} \
    -set colorspace RGB \
    -pointsize 32 \
    -fill "blue" \
    -stroke "blue" \
    -draw "stroke-linecap butt" \
    -strokewidth 3 \
    "${drawCmds[@]}" \
    -colorspace sRGB \
    ${OIMFILE}
