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)


###------------------------------------------------------------------------------
# Set the input folder containing GeoTIFF files
input_folder <- "/home/abarrant/esarchive/scratch/abarrant/satellites/EarthEngine_NO2/geoTIF"
output_folder <- "/home/abarrant/esarchive/scratch/abarrant/satellites/EarthEngine_NO2/netCDF_cat"

# Create the output folder if it doesn't exist
if (!dir.exists(output_folder)) {
  dir.create(output_folder)
}

# List all GeoTIFF files in the input folder
tif_files <- list.files(input_folder, pattern = "\\.tif$", full.names = TRUE)
crop_extent <- ext(0.006, 3.523, 40.194, 43.069) #cat box

# Loop through each GeoTIFF file and convert to NetCDF
for (tif_file in tif_files) {
  #tif_file <- tif_files[3]
  # Load the GeoTIFF file
  r <- rast(tif_file)
  r_cropped <- crop(r, crop_extent) #cropping into the catalan box
  
  # Define the output NetCDF file name
  output_file <- file.path(output_folder, paste0(tools::file_path_sans_ext(basename(tif_file)), ".nc"))
  
  # Write the raster to a NetCDF file
  writeCDF(r_cropped, output_file, overwrite = TRUE)
  
  # Print status
  cat("Converted:", tif_file, "to", output_file, "\n")
}

cat("All files have been converted successfully.\n")


