#! /bin/bash -eu
# Last edited on 2026-06-20 10:44:58 by stolfi

# Extracts a specified rectbagle from three multispectral images of a given page.
# Combines them as the R, G, B channels of a color PNG image "raw.png", with a 
# 60-pixel gray border.

MS="${HOME}/projects/voynich/MultiSpectral/davis"
WORK="${HOME}/projects/voynich/work"
BIN="${HOME}/bin"

page="$1"; shift

bandR="$1"; shift
minvalR="$1"; shift
maxvalR="$1"; shift

bandG="$1"; shift
minvalG="$1"; shift
maxvalG="$1"; shift

bandB="$1"; shift
minvalB="$1"; shift
maxvalB="$1"; shift

matrix="$1"; shift

crop="$1"; shift
rot="$1"; shift     # Argument of ImageMagick's "-rotate" or "NONE".
bsize="$1"; shift   # Argument for ImageMagick's "-border".
pctmag="$1"; shift  # Percent magnification/shrinking, or "NONE".

resize_ops=( )
if [[ "/${pctmag}" != "/NONE" ]]; then
  pctmag="${pctmag}%"
  pctmag="${pctmag/%%/%}"
  if [[ "/${pctmag}" != "/100%" ]]; then
    resize_ops=( "-resize" "${pctmag}" )
    echo "resize_ops = ${resize_ops[*]}" 1>&2
  fi
fi

rotate_ops=( )
if [[ "/${rot}" != "/NONE" ]]; then
  if [[ "/${rot}" != "/0" ]]; then
    rotate_ops=( "-rotate" "${rot}" )
    echo "rotate_ops = ${rotate_ops[*]}" 1>&2
  fi
fi

if [[ "/${matrix}" == "/NONE" ]]; then
  matrix="1.0 0.0 0.0  0.0 1.0 0.0  0.0 0.0 1.0"
fi

# Extract clips of each band and adjust brightness:
bands=( ${bandR} ${bandG} ${bandB}  )
minvals=( ${minvalR} ${minvalG} ${minvalB}  )
maxvals=( ${maxvalR} ${maxvalG} ${maxvalB}  )

for ib in 0 1 2; do
  band="${bands[${ib}]}"
  maxval="${maxvals[${ib}]}"
  minval="${minvals[${ib}]}"
  convert \
    ${MS}/${page}/${band}/full.png \
    +repage \
    -crop "${crop}" \
    ${resize_ops[@]} \
    ${rotate_ops[@]} \
    -level ${minval},${maxval} \
    .${band}.png 
done

# Create a composite image "raw.png"
convert \
  .${bands[0]}.png \
  .${bands[1]}.png \
  .${bands[2]}.png \
    -combine \
    -color-matrix "${matrix}" \
    -auto-level \
    -bordercolor "rgb(50%,50%,50%)" \
    -border "${bsize}" \
    +repage \
    -flatten \
    raw.png
