#! /bin/bash -eu
# Last edited on 2026-06-18 18:23:00 by stolfi

# Extracts a grayscale clip from a specified grayscale source image,
# puts a 50% gray border around it

USAGE="$0 SOURCE_FILE CROP ROT MAXVAL BORDER_SIZE PCTMAG"

if [[ $# -ne 7 ]]; then
  echo "** missing/spurious arguments - usage:\n ${USAGE}" 1>&2; exit 1
fi
pfile="$1"; shift   # Page image.
crop="$1"; shift    # Argument of ImageMagick's "-crop".
rot="$1"; shift     # Argument of ImageMagick's "-rotate" or "NONE".
minval="$1"; shift  # Min sample value for scaling.
maxval="$1"; shift  # Max sample value for scaling.
bsize="$1"; shift   # Argument for ImageMagick's "-border".
pctmag="$1"; shift  # Percent magnification/shrinking, or "NONE".

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

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

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 Gray \
    -level ${minval},${maxval} \
    -bordercolor 'gray(50%)' \
    -border "${bsize}" \
    +repage \
    -flatten \
    raw.png 

