#!/bin/bash

year=2011
cdo=/cluster/gcc-4.8.5/tools/bin/cdo
path=/data3/data/HYCOM/hindcasts/GLBv0.08/2011/D20

for i in {01..01..01}
do
    mkdir -p ${path}/${i}

    if [ ${i} -ge 7 ] ;then
        vv=537
    else
        vv=536
    fi

    rm -rf ${path}/${i}/record.txt

    cd ${path}/${i}

    for j in {01..01..01}
    do
        for k in {00..00..06}
        do
            file=${path}/../${i}/hycom_GLBv0.08_${vv}_2011${i}${j}12_t0${k}.nc
            output_file=hycom_D20_2011${i}${j}12_t0${k}.nc

            if [[ -f ${output_file} ]]; then
                panosize=$(stat -c%s "$output_file")
            else
                panosize=0
            fi

            # 如果檔案不存在或大小異常，則進行計算
#            if [[ ! -f ${output_file} ]] || [[ ${panosize} -le 29000000 ]]; then
                echo "Processing ${output_file} ..."

                # 1. 提取 water_temp 和 depth 變數
                cdo selvar,water_temp,depth ${file} temp.nc
                
                # 2. 應用 scale_factor 和 add_offset
                cdo mulc,0.001 temp.nc temp_scaled.nc
                cdo addc,20 temp_scaled.nc temp_final.nc

                # 3. 找出水溫 20°C 對應的深度
                cdo eqc,20 temp_final.nc mask_20C.nc
                cdo mul mask_20C.nc temp_final.nc depth_at_20C.nc  # 這裡的 depth 是原始檔案內的變數

                # 4. 計算水溫 20°C 的平均深度
                cdo fldmean depth_at_20C.nc ${output_file}

                echo "Created ${output_file}"
#                rm -rf temp.nc temp_scaled.nc temp_final.nc mask_20C.nc depth_at_20C.nc
#            fi
            # 紀錄檔案處理狀態
            if [ -f ${output_file} ]; then
                echo "${i}${j}_t0${k} ok" >> record.txt
            else
                echo "${i}${j}_t0${k} false" >> record.txt
            fi
        done
    done
done

