#!/bin/bash

# =========================================================
# Set_data_2
# Crop merged monthly datasets to the study domain
# Domain: 60°S–60°N, 180°W–180°E
# Variables used in this study:
#   chl-a, SST, SSHF, MLD, WS, NO3, PO4, Fe, Si
# =========================================================

# Input directory from Set_data_1
INPUT_DIR="./merged_data"

# Output directory for cropped datasets
OUTPUT_DIR="./cropped_data"
mkdir -p "${OUTPUT_DIR}"

# Variable list
variables=(
    "chl_a"
    "SST"
    "SSHF"
    "MLD"
    "WS"
    "NO3"
    "PO4"
    "Fe"
    "Si"
)

echo "Starting spatial cropping..."

for var in "${variables[@]}"; do
    input_file="${INPUT_DIR}/${var}_monthly_merged.nc"
    output_file="${OUTPUT_DIR}/${var}_cropped.nc"

    if [[ ! -f "${input_file}" ]]; then
        echo "Input file not found: ${input_file}"
        continue
    fi

    echo "Cropping ${var} ..."
    cdo sellonlatbox,-180,180,-60,60 "${input_file}" "${output_file}"

    if [[ $? -eq 0 ]]; then
        echo "Completed: ${output_file}"
    else
        echo "Cropping failed: ${input_file}"
    fi
done

echo "All cropping tasks finished."