#! /bin/bash -eu
# Last edited on 2026-01-02 23:40:48 by stolfi

# To be included in bash shell scripts.
# Defines the function {grab_clip} that extracts a clip from an image with specified
# position, size, and rotation.

function grab_clip() {
  # Defines the function that takes arguments
  #
  #  {ifile} {odir} {num} {iwd} {iht} {idx} {idy} {rot} {owd} {oht} {odx} {ody}
  #
  # The function extracts a rectangle from an image,
  # rotates it by a specified angle, then extracts from that 
  # another rectange, and saves it as a file "{odir}/{num}.png".
  # Also labels the extracted clip with {num}

  ifile=$1; shift
  odir=$1; shift
  num=$1; shift
  iwd=$1; shift
  iht=$1; shift
  idx=$1; shift
  idy=$1; shift
  rot=$1; shift
  owd=$1; shift
  oht=$1; shift
  odx=$1; shift
  ody=$1; shift
  
  convert ${ifile} \
    -crop "${iwd}x${iht}+${idx}+${idy}" -rotate ${rot} +repage \
    -crop "${owd}x${oht}+${odx}+${ody}" +repage \
    -fill 'rgb(90%,80%,60%)' \
    -draw 'rectangle 5,5 31,23' \
    -fill 'rgb(40%,0%,100%)' -font Courier-Bold -pointsize 20 \
    -gravity NorthWest \
    -draw "text 7,3 '${num}'" \
    ${odir}/${num}.png 
}
