#!/usr/bin/env bash
# stitch multiple screenshots into a panorama
# based on run-scan-pto_var.sh (Terry Duell 2013, 2014)

. lib.bash || exit

usage() {
	echo "Usage: $progname [-o output] <input_file>..."
	echo
	echo_opt "-o PREFIX" "output file prefix"
	echo_opt "-S" "stop and interactively inspect before execution"
	echo
	echo "By default, output is named after last input with '*_stitch.tif' suffixed."
}

prefix=""
do_trash=0
do_stop=0

while getopts ':o:TS' OPT; do
	case $OPT in
	o) prefix=$OPTARG;;
	T) do_trash=1;;
	S) do_stop=1;;
	*) lib:die_getopts;;
	esac
done; shift $((OPTIND-1))

src_files=("$@")

if [[ ! $src_files ]]; then
	die "input files not specified"
fi
if (( $# < 2 )); then
	die "only one input was specified; doing nothing"
fi

if [[ ! $prefix ]]; then
	prefix="${@:$#}"
	prefix="${prefix%.*}_stitch"
fi

dir=$(mktemp -d /tmp/stitch_pto.XXXXXX)
fov=10

log2 "creating project"

pto_gen --projection=0 --fov="${fov:-10}" -o "$dir/0.pto" "${src_files[@]}"

spec=$(printf ",i%d" "${!src_files[@]}")
pto_lensstack --new-lens "${spec#,}" -o "$dir/1.pto" "$dir/0.pto"

log2 "detecting image features"

cpfind --multirow                   -o "$dir/2.pto" "$dir/1.pto"
cpclean                             -o "$dir/3.pto" "$dir/2.pto"
linefind                            -o "$dir/4.pto" "$dir/3.pto"

log2 "repositioning images"

pto_var --opt r,d,e,!r0,!d0,!e0     -o "$dir/5.pto" "$dir/4.pto"
autooptimiser -n                    -o "$dir/6.pto" "$dir/5.pto"

log2 "stitching images"

pano_modify --projection=0 --fov=AUTO --center --canvas=AUTO --crop=AUTO -o "$dir/7.pto" "$dir/6.pto"

if (( do_stop )); then
	hugin "$dir/7.pto"
fi
hugin_executor --stitching --prefix="$prefix" "$dir/7.pto"
#hugin_stitch_project --output="$prefix" "$dir/7.pto"

log2 "cleaning up"

rm -rf "$dir"
if (( do_trash )); then
	vmsg "Trashing input files"
	trash "${src_files[@]}"
fi

msg "Output: $prefix.tif"
