# -------------------------------------------------------- #
# function starting Gadgetron if necessary
# -------------------------------------------------------- #
function start_gadgetron {
	if [[ "$(pgrep gadgetron)" == "" ]]; then
		echo Starting a gadgetron server
		open -a Terminal.app $(which gadgetron)
		sleep 3
	fi
}

# -------------------------------------------------------- #
# Raw MR .dat to .h5
# -------------------------------------------------------- #
raw_mr_dat=$(find . \( -name "meas*.dat" -or -name "2019*.dat" \))
raw_mr_h5=${raw_mr_dat:0:-4}.h5
if [ -f "$raw_mr_h5" ]; then
	echo not running siemens_to_ismrmrd as file already exists: ${raw_mr_h5}
else
	echo "siemens_to_ismrmrd -f ${raw_mr_dat} -o ${raw_mr_h5}"
	siemens_to_ismrmrd -f ${raw_mr_dat} -o ${raw_mr_h5}
fi

# -------------------------------------------------------- #
#                                                          #
#                           SIRF                           #
#                                                          #
# -------------------------------------------------------- #
# 1. Recon with SIRF
# 2. Use SIRF to convert to NIfTI

SIRF_recon_no_extension=SIRF_recon
SIRF_recon_h5=${SIRF_recon_no_extension}.h5
SIRF_recon_nii=${SIRF_recon_no_extension}.nii

if [ -f "${SIRF_recon_nii}" ]; then
	echo not running reconstruction as file already exists: ${SIRF_recon_nii}
else
	# Run gadgetron if not already running
	start_gadgetron
	
	# 1. Recon with SIRF
	path_to_recon="${SIRF_PATH}/examples/Python/MR/Gadgetron/fully_sampled_recon_single_chain.py"
	echo $SIRF_PYTHON_EXECUTABLE "${path_to_recon}" -f ${raw_mr_h5} -p . -o ${SIRF_recon_no_extension} --type_to_save=mag -a GenericReconCartesianFFTGadget
	$SIRF_PYTHON_EXECUTABLE "${path_to_recon}" -f ${raw_mr_h5} -p . -o ${SIRF_recon_no_extension} --type_to_save=mag -a GenericReconCartesianFFTGadget
	if [[ "$?" != "0" ]]; then exit 1; fi

	# 2. Use SIRF to convert to NIfTI
	sirf_convert_image_type ${SIRF_recon_nii} nii ${SIRF_recon_h5} Gadgetron
fi