#!/bin/bash
################################################################
### Script to concatenate "diagpem.nc" outputs into one file ###
################################################################

# Output file name
output_file="diagpem_concat.nc"

# Frequency of PEM outputs
ecritpem=1

# Number of initial PCM calls
nPCM_ini=4

# Number of GCM calls between each PEM call
nPCM=2

# List of NetCDF files to concatenate
directory="diags"
files=($directory/diagpem*.nc)
output_file=($directory/$output_file)


################################################################
# Checking if everything is ok
if [ ! -d "$directory" ]; then
    echo "Error: directory \"$diags\" not found!"
    exit 1
fi
if [ ${#files[@]} -lt 2 ]; then
    echo "Error: there are not enough files for concatenation!"
    exit 1
fi
if [ -f "$output_file" ]; then
    rm $output_file
fi

# Loop to concatenate the NetCDF files
newTime=$((nPCM_ini + 1))
for file in "${files[@]}"; do
    # Extract the 'Time' variable into a temporary file
    ncks -v Time "$file" > tmp_Time.txt

    # Extract the 'data' block containing the Time values
    data_block=$(awk '/data:/ {flag=1} flag; /\}/ {flag=0}' tmp_Time.txt | sed '1d;$d')
    data_block=$(echo "$data_block" | sed -e 's/^[ \t]*//')
    data_block=$(echo "$data_block" | sed 's/Time =//')
    data_block=$(echo "$data_block" | sed 's/;$//')
    IFS=', ' read -ra Time_values <<< "$data_block"

    # Remove the temporary file
    rm tmp_Time.txt

    # Updating the variable 'Time' with the number of the year
    for ((i=0; i < ${#Time_values[@]}; i++)); do
        ncap2 -O -s "Time($i)=$newTime" $file $file
        newTime=$((newTime + ecritpem))
    done
    
    # Concatenate the NetCDF file to the output
    if [ ! -f "$output_file" ]; then
        cp $file $output_file
    else
        ncrcat -O $output_file $file -o $output_file
    fi
    newTime=$((newTime + nPCM))
done

echo "Concatenation of \"$directory/diagpem*.nc\" files into \"$output_file\" is complete!"
