#!/bin/bash

if [ $# -eq 0 ]
  then
    echo -e "\n\tNo arguments supplied."
    echo -e "\tYou need to supplied the worker dir.\n"
    echo -e "\tSYNOPSIS"
    echo -e "\t\t./alignNii.sh [PATH-TO-IMAGES-FOLDERS]\n"
    echo -e "\tExample"
    echo -e "\t\t./alignNii.sh /Users/root/Documents/ADNI\n\n"
    exit 1
fi

# save actual dir
ROOT=$(pwd)

# go to images dir
cd $1

find $(pwd) -name \*.nii | sort | while read line; do

    # get file folder name
    DIR=$(dirname "${line}")

    # get file name
    FILENAME=$(basename "$line")

    # output folder name
    acpcAlignment="$DIR/acpcAlignment"

    # delete output folder if exist with all the content
    if [ -d "$acpcAlignment" ]; then
        rm -rf "$acpcAlignment"
    fi

    # create output folder
    mkdir "$acpcAlignment";

    # copy .nii file to output folder
    cp -- "$line" $acpcAlignment

    echo -e "Directory: $line"

    # change dir to output folder
    cd $acpcAlignment

    # run acpcdetect command to align the nifti
    acpcdetect -center-AC -i "$acpcAlignment/$FILENAME"

    # delete .nii file from output folder
    rm "$acpcAlignment/$FILENAME"

done

# go to original dir
cd $ROOT
