#!/bin/bash

downscaling_luh2() {
  # Arguments
  local input_nc=$1
  local output_dir=$2
  local resolution=$3
  local output_width=$4
  local output_height=$5
  local xmin=$6
  local ymin=$7
  local xmax=$8
  local ymax=$9

  # Extract the year from the input filename
  local year=$(basename $input_nc | grep -oP '\d{4}')

  # Compute the resolution
  local x_resolution=$(echo "scale=10; ($xmax - $xmin) / $output_width" | bc)
  local y_resolution=$(echo "scale=10; ($ymax - $ymin) / $output_height" | bc)

  # Loop through each data subdataset (ignoring lat_bounds and lon_bounds)
  for i in {1..14}
  do
      local subdataset_name=$(gdalinfo $input_nc | grep "SUBDATASET_${i}_NAME" | cut -d '=' -f 2)
      local subdataset_desc=$(gdalinfo $input_nc | grep "SUBDATASET_${i}_DESC" | cut -d '=' -f 2 | cut -d ' ' -f 1)
      local variable_name=$(basename $subdataset_name)
      variable_name=${variable_name##*:}
      local output_nc="${output_dir}/${variable_name}_${year}_${resolution}deg.nc"
      
      echo "Processing $subdataset_name -> $output_nc"
      
      # Process each subdataset with NetCDF-4, chunking, and compression
      gdalwarp -tr $x_resolution $y_resolution -te $xmin $ymin $xmax $ymax -r bilinear -of netCDF \
        -co "FORMAT=NC4" -co "COMPRESS=DEFLATE" -co "ZLEVEL=9" \
        "$subdataset_name" "$output_nc"
      
      # Rename the variable in the output file
      ncrename -v Band1,$variable_name "$output_nc"
  done

  # Combine all individual NetCDF files into a single NetCDF file
  local combined_nc="${output_dir}/$(basename $input_nc .nc)_${resolution}deg.nc"

  # Initialize the combined file with the first subdataset
  cp ${output_dir}/$(basename $(gdalinfo $input_nc | grep "SUBDATASET_1_NAME" | cut -d '=' -f 2) | cut -d ':' -f 2)_${year}_${resolution}deg.nc "$combined_nc"

  # Loop through the remaining subdatasets to merge them
  for i in {2..14}
  do
      local variable_name=$(basename $(gdalinfo $input_nc | grep "SUBDATASET_${i}_NAME" | cut -d '=' -f 2) | cut -d ':' -f 2)
      local output_nc="${output_dir}/${variable_name}_${year}_${resolution}deg.nc"
      
      echo "Adding $variable_name to $combined_nc"
      
      ncks -A "$output_nc" "$combined_nc"
  done

  echo "All subdatasets processed and combined into $combined_nc"

  # Clean up individual files if desired
  # rm ${output_dir}/*.nc

  echo "Processing complete."
}

# Call the function with the passed arguments
#              "$input_nc" "$output_dir" "$resolution" "$output_width" "$output_height" "$xmin" "$ymin" "$xmax" "$ymax"
downscaling_luh2 "$1" "$2" "$3" "$4" "$5" "$6" "$7" "$8" "$9"
