#!/bin/bash
#
# binn  input_filename  output_filename  binning_factor
#
# Take a photo and shrink it by the binning_factor to improve
# signal to noise ratio.  Binning factor must be a whole number,
# and input image may be cropped slightly to ensure its size is a
# whole number of 'bins'.
#
# Original Script by Walter Dnes <waltdnes@waltdnes.org>

source_file=${1}
output_file=${2}
bin_size=${3}

set -$- `identify -format '%w %h' ${1}`
x=$1   y=$2

newx=$((${x} / ${bin_size}))
checkx=$((${newx} * ${bin_size}))
if [[ ${checkx} -ne ${x} ]]; then
  crop_flag="YES"
fi

newy=$((${y} / ${bin_size}))
checky=$((${newy} * ${bin_size}))
if [[ ${checky} -ne ${y} ]]; then
  crop_flag="YES"
fi

if [ "$crop_flag" ]; then
  crop_args="-crop '${checkx}x${checky}+0+0' +repage"
fi

convert ${source_file} $crop_args \
        -filter box -resize "${newx}x${newy}" \
        ${output_file}

