#! /bin/bash
# Last edited on 2025-08-09 22:04:10 by stolfi
# 
# If ${makein} is true, also writes 
# a PNG file "${dir}/in.png", is a copy of "${full_pgm}" except that
# everything outside a specified rectangle is blacked out.
#  The "in.pgm" file
# is full size. It will look almost black because they use only
# 10 or 11 bit of the 16 bits per sample.
# Also creates a binary image "${dir}/in_over.png" showing where 
# "${dir}/in.png" has samples that exceed {maxval}.
#
# Also creates PNG color-norlaized versions of "${dir}/in.png"
# scaled to 1/16 of full size, with name "${dir}/sma.png".
# 
makein="$1"; shift     # Make the "in.pgm" image? (0 or 1). 
echo "  makein = ${makein}" 1>&2

hmaxval=`printf "%04x" ${maxval}`
echo "  maxval = '#${hmaxval}' = ${maxval}" 1>&2

hblack="#000000000000"
hwhite="#${hmaxval}${hmaxval}${hmaxval}"

  # echo "" \
  #   -level-colors "${hblack},${hwhite}" \
  # 

if [[ ${makein} -eq 0 ]]; then exit 0; fi

# Extract the page image proper:
ofile_in="${dir}/in.pgm"
echo "creating ${ofile_in} ..." 1>&2
convert ${full_pgm} \
    -set colorspace LinearGray \
    \( ${full_pgm} -colorspace Gray -threshold '100%' -fill white -draw "rectangle ${p1} ${p2}" \) \
    -compose multiply \
    -composite \
    ${rotcmd[@]} \
    -colorspace LinearGray \
    ${ofile_in}
ls -l ${tfile_in} ${ofile_in}

# Create histograms:
for ff in ${ofile_in} ; do
  ff_hist="${ff/.*}_hist.png"
  echo "creating ${ff_hist} ..." 1>&2
  plot_msi_png_histogram.sh ${ff} 4095 > ${ff_hist}
  show_image ${ff_hist}
done

# Create image with overvalued pixels:
for ff in ${ofile_in} ; do
  ff_over="${ff/.*}_over.png"
  echo "creating ${ff_over} ..." 1>&2
  show_overexp_pixels.sh ${ff} ${maxval} > ${ff_over}
  show_image ${ff_over}
done
  
# Create smaller versions:
convert ${dir}/in.png -resize '6.25%' -normalize -depth 8 PNG:${dir}/in_sma.png
show_image ${dir}/in_sma.png ${ofile_in}
