############################################
#
# Script for Siril 1.4
# December 2024
# (C) Cyril Richard
# ExtractHaOIII v1.5
#
########### PREPROCESSING SCRIPT ###########
#
# Script for color camera preprocessing that
# extracts Ha and OIII
#
# Needs 4 sets of RAW images in the working
# directory, within 4 directories:
#   biases/
#   flats/
#   darks/
#   lights/
# Saves masters to ./masters/
#
############################################

requires 1.3.4

# Convert Bias Frames to .fit files
cd biases
convert bias -out=../process
cd ../process

# Stack Bias Frames to bias_stacked.fit
stack bias rej 3 3 -nonorm -out=../masters/bias_stacked
cd ..

# Convert Flat Frames to .fit files
cd flats
convert flat -out=../process
cd ../process

# Calibrate Flat Frames
calibrate flat -bias=../masters/bias_stacked

# Stack Flat Frames to pp_flat_stacked.fit
stack pp_flat rej 3 3 -norm=mul -out=../masters/pp_flat_stacked
cd ..

# Convert Dark Frames to .fit files
cd darks
convert dark -out=../process
cd ../process

# Stack Dark Frames to dark_stacked.fit
stack dark rej 3 3 -nonorm -out=../masters/dark_stacked
cd ..

# Convert Light Frames to .fit files
cd lights
convert light -out=../process
cd ../process

# Calibrate Light Frames
calibrate light -dark=../masters/dark_stacked -flat=../masters/pp_flat_stacked -cc=dark -cfa -equalize_cfa

# Extract Ha and OIII
seqextract_HaOIII pp_light -resample=ha

# Align Ha lights
register Ha_pp_light

# Stack calibrated Ha lights to Ha_stack (temporary)
stack r_Ha_pp_light rej 3 3 -norm=addscale -output_norm -32b -out=results_00001

# and flip if required
mirrorx_single results_00001

# Align OIII lights
register OIII_pp_light

# Stack calibrated OIII lights to OIII_stack (temporary)
stack r_OIII_pp_light rej 3 3 -norm=addscale -output_norm -32b -out=results_00002

# and flip if required
mirrorx_single results_00002

# Align the result images, small shifts and chromatic aberrations can occur
register results -transf=shift -interp=none

# Renorm OIII to Ha using PixelMath
pm $r_results_00002$*mad($r_results_00001$)/mad($r_results_00002$)-mad($r_results_00001$)/mad($r_results_00002$)*median($r_results_00002$)+median($r_results_00001$)
save ../results/result_OIII_$LIVETIME:%d$s

# Save Ha final result
load r_results_00001
save ../results/result_Ha_$LIVETIME:%d$s

close
