#! /bin/bash -eu
# Last edited on 2025-12-15 22:17:18 by stolfi

# Extracts a clip from a specified source image,
# puts a border around it, samples a color from that same
# source image.

USAGE="$0 SOURCE_FILE CROP BORDER_SIZE BG_PIXEL"

if [[ $# -lt 4 ]]; then
  echo "** missing arguments - usage:\n ${USAGE}" 1>&2; exit 1
fi
pfile="$1"; shift   # Page image.
crop="$1"; shift    # Argument of ImageMagick's "-crop".
bsize="$1"; shift   # Argument for ImageMagick's "-border".
bpixel="$1"; shift  # Pixel of parent image for the border color.
if [[ $# -ge 1 ]]; then
  pctmag="$1"; shift  # Percent magnification/shrinking.
else
  pctmag="NONE"
fi
if [[ $# -ge 1 ]]; then
  rot="$1"; shift  # Percent magnification/shrinking.
else
  rot="NONE"
fi
if [[ $# -gt 0 ]]; then
  echo "** spurious arguments [$*]" 1>&2; exit 1
fi

pdir="${HOME}/programs/bash/js_image_tools"

if [[ ${pfile} == "NONE" ]]; then
  echo "** page image can't be NONE" 1>&2; exit 1
fi

# Extract the raw patch from the Beinecke 2014 scans.

# Get the average clean parch color ${bcolor}:
xbpixel=`echo "scale=0; ${bpixel/,*/}/20" | bc -lq`
ybpixel=`echo "scale=0; ${bpixel/*,/}/20" | bc -lq`
convert \
  ${pfile} \
  -resize '5%' \
  -print "bcolor='%[pixel:p{${xbpixel},${ybpixel}}]'\n" \
   null: \
   > .bcolor
cat .bcolor 1>&2

# Extract the raw image clip:
source .bcolor

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

convert \
  ${pfile} \
  -crop "${crop}" \
  ${resize_ops[@]} \
  ${rotate_ops[@]} \
  -colorspace sRGB \
  -bordercolor "${bcolor}" \
  -border "${bsize}" \
  +repage \
  -flatten \
  raw.png

