#!/bin/bash
##################################################
# Jan 2022
# SuperStack V0.1
# C. Melis (C)
# This script stacks multiple images of a sequence
# to create superstacks
# It assumes frame numbers are contiguous
# in the input sequence and image numbering
# starts at 1
##################################################

# User settings
nbframes=3 # default number of frames in each super stack
step=1 # default number of frames between each super stack
seqname=comet_ # name of the registered sequence
stackfolder=superstack # output subfolder
processfolder=process # name of the subfolder which contains the sequence
ext=fit # chosen fits extension
method='mean 3 3' # stacking method
tempfolder=tmp #temporary folder name (will be deleted at the end)

# User command line inputs if any
if [ ! -z "$1" ]; then nbframes=$1; fi
if [ ! -z "$2" ]; then step=$2; fi
if [ ! -z "$3" ]; then seqname=$3; fi
if [ ! -z "$4" ]; then stackfolder=$4; fi
if [ ! -z "$5" ]; then processfolder=$5; fi
if [ ! -z "$6" ]; then ext=$6; fi

printf "Number of frames per superstack: %d\n" $nbframes
printf "Step between each stack: %d\n" $step
printf "Processing sequence: /%s/%s.seq\n" $processfolder $seqname
printf "Superstack saved to folder: %s\n" $stackfolder
printf "FITS extension: %s\n" $ext

# prepare tmp and out folders
# do not force creation to give a chance to correct
# before overwriting

mkdir $tempfolder || exit 1
mkdir $stackfolder || exit 1

#parse the .seq file to find total number of frames
while read line
do
  if [[ "$line" =~ ^[^#] ]]; then spec=($line); break; fi
done < $processfolder/$seqname.seq
total=${spec[3]}
if [ -z "$total" ]; then echo "Could not parse sequence file"; exit 1; fi
printf "\nNumber of frames in the sequence: %d\n" $total

# get siril version
version=$(siril --version |awk '{print $2}')

# looping until the last frame frame of a superstack
# is larger than total number of frames
NS=1
NE=$(($NS+$nbframes-1))
c=0
while :
do
  [[ $NE -le $total ]] || break
  printf "Superstack#%d: %d-%d\n" $((c+1)) $NS $NE
  for i in $(seq 1 $nbframes); do #copying subframes
    SRC=$(printf "$seqname%05d.$ext" $((NS-1+i)))
    ln -s ../$processfolder/${SRC} $tempfolder/${SRC}
  done
  siril-cli -s - <<ENDSIRIL >log 2>&1
requires $version
setext $ext
cd $tempfolder
stack $seqname $method -nonorm
cd ..
ENDSIRIL
  supstack=$(printf "superstack_$seqname%05d.$ext" $((c+1)))
  mv $tempfolder/${seqname}stacked.$ext $stackfolder/$supstack
  rm $tempfolder/* #emptying temp folder
  NS=$(($NS+step))
  NE=$(($NS+$nbframes-1))
  c=$((c+1))
done

printf "Number of superstacks: %d\n" $c
rm -rf $tempfolder
