#! /bin/bash
# Last edited on 2024-04-01 16:38:47 by stolfi

# Converts a pair of linear-scale ppm files, generated
# with black and white backgrounds, respectively,
# to a gamma-corrected, transparent-background PNG file  
# unsing the standard 6x6x6 colormap.
# The output is sent to stdout.

# Program paths:

# Option parsing:

scriptname="$0"
usagetail="BLACKFILE.ppm WHITEFILE.ppm > OUTFILE.png"
source ${STOLFIHOME}/lib/linear-ppm-to-png-options.sh

if [[  $# != 2  ]]; then
  echo "usage: ${usage}"
  exit 1
fi

blackppm="$1"
whiteppm="$2"

tmp="/tmp/$$"
blacktmp="${tmp}-0.ppm"
whitetmp="${tmp}-1.ppm"
difftmp="${tmp}-d.ppm"
masktmp="${tmp}-m.pgm"
pngraw="${tmp}-r.png"
pngtmp="${tmp}-p.png"

${getimg} ${blackppm} > ${blacktmp}
${getimg} ${whiteppm} > ${whitetmp}

pnmpairtopng ${blacktmp} ${whitetmp} \
  > ${pngraw}
  
cat ${pngraw} \
  | convert \
      PNG:- \
      -gamma ${gamma} \
      PNG:- \
  > ${pngtmp}

# Attempt using pnmxarith etc:
# 
# pnmxarith -subtract \
#     "${whitetmp}" "${blacktmp}" \
#   > ${difftmp}
#     
# cat ${difftmp} \
#   | ppmtopgm \
#   | pnminvert \
#   | pnmdepth 255 \
#   > ${masktmp}
#   
# cat ${blacktmp} \
#   | pnmgamma ${gamma} \
#   | pnmtopng \
#     -force \
#     -gamma ${ammag} \
#     -alpha ${masktmp} \
#   > ${pngtmp}

# identify -verbose ${pngtmp} 1>&2
# 
# qpngtmp="${tmp}-q.png"
# cpngtmp="${tmp}-c.png"
# qgiftmp="${tmp}-q.gif"
#  
# # Just checking: 
# mattetmp="${tmp}-t.pgm"
# convert \
#     ${pngtmp} \
#     -matte \
#     PGM:- \
#   > ${mattetmp}
# display ${mattetmp} &
#   
# composite \
#     -compose Over \
#     ${pngtmp} \
#     bground.ppm \
#     PNG:- \
#   > ${cpngtmp}
  
cat ${pngtmp}

# display -title '%f' ${pngtmp} ${tmp}-*.{ppm,pgm,png,gif}

/bin/rm -f ${tmp}-*

