﻿#!/bin/bash
# Global Cortical SUVR & Centiloid Calculation Script
set -e

if [ -z "$1" ]; then
    echo "Usage: $0 <subject_id>"
    echo "Example: $0 02"
    exit 1
fi

subject_id=$1
subject="sub-${subject_id}"

echo "Analyzing Subject: ${subject}"

echo "Changing directory to the subject's folder..."
cd ~/Desktop/derivatives/data/${subject}/

echo "Loading software modules..."
if ! ml fsl/6.0.7.8 2>/dev/null; then
    echo "Specific fsl version not found, trying default..."
    ml fsl
fi

if ! ml freesurfer/7.3.2 2>/dev/null; then
    echo "Specific freesurfer version not found, trying default..."
    ml freesurfer
fi

CENTILOID_SUVR_ZERO=1.009
CENTILOID_SUVR_100=2.076

SCRIPT_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
PROJECT_ROOT="$(dirname "$(dirname "$SCRIPT_DIR")")"
MASK_DIR="${PROJECT_ROOT}/data/references/centiloid_masks"

if [ ! -d "$MASK_DIR" ]; then
    echo "WARNING: Mask directory not found at expected relative path:"
    echo "$MASK_DIR"
    echo "Please ensure the 'data/references/centiloid_masks' folder is in the project root."
    exit 1
fi

ref_mask="${MASK_DIR}/voi_WhlCbl_2mm.nii"
target_mask="${MASK_DIR}/voi_ctx_2mm.nii"

mni_pet_image="pet/${subject}_pet_to_MNI_smoothed.nii.gz"

output_csv=${2:-"${subject}_global_cortical_results.csv"}

if [ ! -f "$mni_pet_image" ]; then
    echo "ERROR: Input PET image not found: $mni_pet_image"
    exit 1
fi

if [ ! -f "$ref_mask" ]; then
    echo "ERROR: Reference mask not found: $ref_mask"
    exit 1
fi

if [ ! -f "$target_mask" ]; then
    echo "ERROR: Target mask not found: $target_mask"
    exit 1
fi

mkdir -p "$(dirname "$output_csv")"

if [ ! -f "$output_csv" ]; then
    echo "Creating new CSV file: $output_csv"
    echo "subject_id,cerebellar_mean,global_cortical_mean,global_cortical_suvr,global_cortical_centiloid" > "$output_csv"
else
    echo "Appending to existing CSV file: $output_csv"
fi

echo "--- Calculating SUVR and converting to Centiloid... ---"

echo "Resampling PET image to match mask geometry..."
resampled_pet="pet/${subject}_pet_resampled_to_mask.nii.gz"
flirt -in "$mni_pet_image" -ref "$ref_mask" -applyxfm -usesqform -out "$resampled_pet"

echo "Calculating mean uptake in Reference Region (Whole Cerebellum)..."
ref_mean=$(fslstats "$resampled_pet" -k "$ref_mask" -M)
echo "Reference Mean: $ref_mean"

echo "Calculating mean uptake in Target Region (Global Cortex)..."
target_mean=$(fslstats "$resampled_pet" -k "$target_mask" -M)
echo "Target Mean: $target_mean"

suvr=$(echo "scale=6; $target_mean / $ref_mean" | bc -l)
echo "Global Cortical SUVR: $suvr"

centiloid_value=$(echo "scale=4; 100 * ($suvr - $CENTILOID_SUVR_ZERO) / ($CENTILOID_SUVR_100 - $CENTILOID_SUVR_ZERO)" | bc -l)
echo "Centiloid Value: $centiloid_value"

echo "$subject,$ref_mean,$target_mean,$suvr,$centiloid_value" >> "$output_csv"

echo ""
echo "--- SCRIPT COMPLETE ---"
echo "Results have been saved to: $output_csv"
