#!/bin/bash
#Terry Duell Mar 2015
# Shell script utility to read a file line by line.
# Once line is read it can be processed in processLine() function
# You can call script as follows,
# ./ais-script2.sh output-prefix
# 
# Run a dir with all your image stacks that want aligned
# using align_image_stack,
# prior to stitching the stacks (linked for position)
# in hugin

# The entries in aislist.txt are the image filenames
# with all the images for each stack in a record.
# the file (aislist.txt) will be prepared by 
# awk and the script formatjpg.awk...see below.
# note formatjpg.awk needs to be set for the number of images per stack,
# as does the following (lines 34-38 and lines 45 and 48

# $1 = image 1
# $2 = image 2
# $3 = image 3
# $4 = image 4
# $5 = image 5

num=1

# User define Function (UDF)
processLine(){
line="$@" # get all args

#  just echo them, so we see that we are reading correctly

im1=$(echo $line | awk '{ print $1 }')
im2=$(echo $line | awk '{ print $2 }')
im3=$(echo $line | awk '{ print $3 }')


# fix output prefix so each run doesn't overwrite last
myprefix="${prefix}${num}"

# now run align_image_stack with this setup
# & runs process in background, hence runs as many as possible in parallel
# add switches align_image_stack command line as required

align_image_stack -a ${myprefix} ${im1} ${im2} ${im3} ${im4} ${im5} &
echo "align_image_stack -a "${myprefix}" ${im1} ${im2} ${im3}"
num=$((num + 1))

# move the aligned images as required
# add your code here
#echo "moved images to"

}
 
### Main script starts here ###

# Store file name
FILE=""
# get the list of files in a groups of stack size
# see awk script formatjpg.awk

ls *.JPG | awk -f formatjpg.awk > aislist.txt
FILE="./aislist.txt"
# get the output prefix
prefix=$1
exec 3<&0
exec 0<$FILE


while read line
do
	# use $line variable to process line in processLine() function
	processLine $line
done

# wait for all background processes to complete
wait

echo "done "
   
exec 0<&3
 
exit 0

