library(raster)
library(sp)
library(ncdf4)
library(terra)


input_file = "/home/abarrant/esarchive/scratch/abarrant/satellites/EarthEngine_NO2/geoTIF/NO2_2023_12-31.tif"
output_file = "/home/abarrant/esarchive/scratch/abarrant/satellites/EarthEngine_NO2/NO2_2023_12-31.nc"



#conversion with raster
r <- raster(input_file)
writeRaster(r, output_file, format = "CDF", overwrite = TRUE)

#conversion with terra
r <- rast(input_file)
writeCDF(r, output_file, overwrite = TRUE)


###------------------------------------------------------------------------------

#input and output folder to get and save the geotiff converted to netcdf
input_folder <- "/home/abarrant/esarchive/scratch/abarrant/satellites/EarthEngine_NO2/geoTIF"
output_folder <- "/home/abarrant/esarchive/scratch/abarrant/satellites/EarthEngine_NO2/netCDF_cat"

#creation of the output directory in case it doesnt exist
if (!dir.exists(output_folder)) {
  dir.create(output_folder)
}

#list of all geotiff files in the input folder
tif_files <- list.files(input_folder, pattern = "\\.tif$", full.names = TRUE)

#catalan box (final dimensions of the nc file)
crop_extent <- ext(0.006, 3.523, 40.194, 43.069) #cat box

#loop through all geotiff files
for (tif_file in tif_files) {
  #tif_file <- tif_files[3]
  
  #loading file
  r <- rast(tif_file)
  r_cropped <- crop(r, crop_extent) #cropping into the catalan box
  
  #output file name
  output_file <- file.path(output_folder, paste0(tools::file_path_sans_ext(basename(tif_file)), ".nc"))
  
  #writing the raster into a netcdf file (and if it exists then it overwrites it)
  writeCDF(r_cropped, output_file, overwrite = TRUE)
  
  #printing status
  cat("Converted:", tif_file, "to", output_file, "\n")
}

#final comment if there has been no error
cat("All files have been converted successfully.\n")

#--------------------------------------

#conversion of tif file altimeter: /home/abarrant/Documents/AQS/geo/euro-dem-tif/data/eurodem.tif
