#! /bin/bash
# Last edited on 2023-09-18 11:28:51 by stolfi

img="$1"; shift
sg="$1"; shift
show="$1"; shift

iimg_dir="align/raw/out"
okys_dir="glyphs/raw/out"
extr_dir="glyphs/raw/out"

ifile="${iimg_dir}/${img}.png"

# Get the side of the disk from the image's name:
side="${img: -1:1}" # The space before "-1" matters!
SIDE=`echo ${side} | tr 'a-z' 'A-Z'`
echo "side = ${side} SIDE = ${SIDE}" 1>&2

okfile="${okys_dir}/${sg}.okys"

OUNIT=0.5 # Pixels per output user unit. 
MAG=4     # Magnification factor for extracted glyphs.

ocpars=( `cat ${okfile} | egrep -e "^${SIDE}[prs]" | sed -e 's/[ ][ ]*/:/g'` )
# echo "ocpars = ( ${ocpars[*]} )" 1>&2

for ocp in "${ocpars[@]}" ; do
  pars=( `echo "${ocp}" | tr ':' ' '` )
  echo "pars = ${pars[*]} (${#pars[*]})" 1>&2
  oc="${pars[0]}"
  sg1="${pars[1]}"
  tp1="${pars[2]}"
  x1="${pars[3]}"
  y1="${pars[4]}"
  r1="${pars[5]}"
  tp2="${pars[6]}"
  x2="${pars[7]}"
  y2="${pars[8]}"
  r2="${pars[9]}"
  if [[ "/${sg1}" != "/${sg}" ]]; then
    echo "** sign code mismatch ${sg} ${sg1}" 1>&2 ; exit 1
  fi
  ofile="${extr_dir}/${sg}/${oc}-${img}.png"

  mkdir -p ${extr_dir}/${sg}
  rm -f ${ofile}

  glyph_extract_one_img_sg_oc.sh \
    ${sg} ${oc} ${img} \
    ${tp1} ${x1} ${y1} ${r1} \
    ${tp2} ${x2} ${y2} ${r2} \
    ${OUNIT} ${MAG} \
    ${ifile} \
    ${ofile}

  if [[ ${show} -ne 0 ]]; then
    if [[ -s ${ofile} ]]; then
      display -title "%f" -filter Box -resize '400%' ${ofile}
    else
      echo "** ${ofile} not generated" 1>&2; exit 1
    fi
  fi
done
