#! /bin/bash 


# USAGE: ${cmd} {STACK_DIR} {SUB}

# Aligns all frames in {STACK_DIR}/{SUB} 
# Writes the result to {STACK_DIR}/align 

dir="$1"; shift;
sub="$1"; shift;

trap "exit 1" SIGINT SIGTERM

cd ${dir} || ( echo "** ${dir} : no such directory" 1>&2 ; exit 1 )

if [[ ! ( -d ${sub} ) ]]; then
  echo "** ${dir}/${sub} missing or not a directory" 1>&2 ; exit 1
elif [[ ! -e ${sub}/frame_00001.jpg ]]; then
  echo "** ${dir}/${sub}/frame_*.jpg : no frames?" 1>&2 ; exit 1
fi

touch ${sub}/frame_DUMMY.jpg # To prevent "no match"
files=( `ls ${sub}/frame_{[0-9][0-9][0-9][0-9][0-9],DUMMY}.jpg | grep -v -e 'DUMMY' | sort` )

if [[ ${#files[@]} -lt 2 ]]; then
  echo "** too few frames - aborted" 1>&2 ; exit 1
fi

mkdir -p align

rm -f align/frame_*.*

align_image_stack \
  -a align/frame_0 \
  -v \
  -m \
  -x \
  -y \
  -z \
  -C \
  -g 5 \
  -p .debug.pto \
  --use-given-order \
  "${files[@]}"
  
# echo "# --------- .debug.pto ---------------------"  
# cat .debug.pto 1>&2
# echo "# ------------------------------------------"  
  
if [[ -s align/frame_00000.tif ]]; then 
  ls -l align/*
  for f in align/frame_[0-9][0-9][0-9][0-9][0-9].tif ; do
    convert $f -alpha Off ${f%.*}.png   
  done
  ls -l align/*.png
  display -title '%f' align/frame_[0-9][0-9][0-9][0-9][0-9].png &
else
  echo "** ${dir} : align failed?" 1>&2 ; exit 1
fi
 
# exit 0
# 
# foo \
#   -d \
#   -i \
#   -s 3 \
 
