#!/bin/sh

if [ $# -lt 2 ] ; then
   printf >&2 %s\\n "$0 <x1>,<y1> <x2>,<y2> [<substitution>]"
   exit 1
fi

# these are the two extremes of the rectangle
p1="$1"
p2="$2"

# optionally take a substitution
substitution="${3:-"s/^/cropped-/"}"

# get x and y min and max positions
x1="${p1%%,*}"
y1="${p1##*,}"
x2="${p2%%,*}"
y2="${p2##*,}"
if [ "$x1" -gt "$x2" ] ; then
   x="$x1"
   x1="$x2"
   x2="$x"
fi
if [ "$y1" -gt "$y2" ] ; then
   y="$y1"
   y1="$y2"
   y2="$y"
fi

# calculate width and height. Both min and max have to be included
# hence the +1
dx=$((x2 - x1 + 1))
dy=$((y2 - y1 + 1))

# this is the "geometry" required by imagemagick
geometry="${dx}x${dy}+${x1}+${y1}"

while read input ; do
   output="$(printf %s "$input" | sed -e "$substitution")"
   convert "$input" -crop "$geometry" +repage "$output" >&2
   printf %s\\n "$output"
done