mkdir -p tmp
HDATE=hdate_2023.txt                # date (mm-dd) to be downloaded
YR1=2003                            # Start year to be downloaded
YR2=2022                            # End year to be downloaded
Prefix=LH_SH_OLR_TP_cf_             # Prefix of filename
PreTTT=TX_TM_cf_                    # Prefix of filename

for iy in {2003..2022}; do
    for idate in `cat hdate_2023.txt`; do
        fname=${Prefix}${iy}-${idate}.nc      # LH_SH_OLR_TP_cf_*
        #if [ -e ${fname} ] ; then
        #   echo ${fnae} " exist"
        #else
        #   echo ${fname} " does not exists"
        #fi
        # File ${fname} tat ca cac bien deu chua tong tich luy tu t=1 den t=47. 
        #De tinh daily values thi lay ngay sau tru ngay truoc: 
        cdo -f nc -b F32 sub -seltimestep,2/47 ${fname} -seltimestep,1/46 ${fname} tmp.nc

        # Cac bien sshf, slhf, ttr co Unit la J/m^2 cua daily (da tinh o tren). Can doi sang don vi W/m^2:
        cdo expr,'sshf=-sshf/86400; slhf=-slhf/86400; ttr=-ttr/86400; tp=tp' tmp.nc tmp1.nc

        # Doi lai Unit cho phu hop:
        ncatted -a units,sshf,m,c,"W m-2" -a units,slhf,m,c,"W m-2" -a units,ttr,m,c,"W m-2" tmp1.nc  

        # Invert latitudes:
        cdo invertlat tmp1.nc tmp.nc

        # Luu vao Thu muc tmp voi cung ten ban dau:
        mv tmp.nc tmp/${fname}
        rm -f tmp1.nc
        # -----------------------------------------------

        fname=${PreTTT}${iy}-${idate}.nc      # TX_TM_cf_*

        # Daily maximum temp: 
        cdo timselmax,4 -selvar,mx2t6 $fname tx.nc

        # Daily minimum temp: 
        cdo timselmin,4 -selvar,mn2t6 $fname tm.nc

        # Ghep Tx va Tm vao cung mot file:
        cdo merge tx.nc tm.nc txm.nc

        # Convert do K sang do C:
        cdo expr,'mx2t6=mx2t6-273.15; mn2t6=mn2t6-273.15' txm.nc txm1.nc

        # Doi Unit K->C
        ncatted -a units,mx2t6,m,c,"C" -a units,mn2t6,m,c,"C" txm1.nc

        # Invert latitudes:
        cdo invertlat txm1.nc tmp.nc

        # Luu vao Thu muc tmp voi cung ten ban dau:
        mv tmp.nc tmp/${fname}
        rm -f tx.nc tm.nc txm.nc
        
    done
done


#cdo -f nc -b F32 sub -seltimestep,2/47 $fname -seltimestep,1/46 $fname tmp/tp_daily.nc # Lay hieu gia tri lien tiep
#cdo expr,'sshf=sshf/86400' output.nc final_output.nc   # Doi sang w/m2
#ncatted -a units,sshf,m,c,"W m-2" final_output.nc      # Doi don vi do

