# non_uniform a data.frame with columns X and Y UTM coordinates and variables (e.g. NO2 concentration)
# target a sp object with @data data.frame with columns for spatial coordinates and and column for the expected values of the variable (e.g. NO2 filled with NAs). The projection in @proj4string needs to be the same as the provided for the non_uniform object and specified in the crs_sim. 
regrid <- function(non_uniform_data, target_grid,
                   crs_sim = "+proj=utm +zone=31 +ellps=intl +units=m +no_defs",
                   nc_path, var_name = NULL, date = NULL, var_units = NULL,
                   var_long_name = NULL, plot = TRUE) {
  # data.frame and SpatialPointsDataFrame:
  non_uniform_data<- sp::SpatialPointsDataFrame(non_uniform_data[,c("X", "Y")],
                                              non_uniform_data)
  sp::proj4string(non_uniform_data) <- crs_sim

  regular <- gstat::idw(NO2 ~ 1, non_uniform_data, newdata = target_grid,
                        idp = 2.0, nmax = 4)
  regular <- sp::spTransform(regular, sp::CRS("+proj=longlat"))
  lon <- unique(round(regular@coords[,1],7))
  lat <- unique(round(regular@coords[,2],7))
  proj <- paste(regular@proj4string@projargs, "+no_defs")
  regular <- regular@data$var1.pred
  dim(regular) <- c(lon = 1450, lat = 1644)
  if (plot == TRUE) {
    fields::image.plot(lon, lat, regular, main = "IDW 4 nearest neighbours",
                       legend.lab = "NO2 concentration",
                       breaks = seq(0, 100, 100/64))
  }
  timedim <- ncdim_def("time", paste("hours since", as.Date(date), "00:00:00"),
                       as.numeric(substr(date, 12, 13)))
  londim <- ncdim_def("lon", "degrees_east", lon, longname = 'longitude')
  latdim <- ncdim_def("lat", "degrees_north", lat, longname = 'latitude')
  var_def <- ncvar_def(var_name, var_units, list(londim, latdim, timedim),
                       longname = var_long_name)
  ncout <- nc_create(file.path(nc_path, paste0(var_name, "_uniform_mesh_",
                               date, ".nc")),
                     vars = var_def, force_v4 = FALSE)
  ncvar_put(ncout, var_def, regular)
  ncatt_put(ncout, var_name, "grid_mapping", "crs")
  ncatt_put(ncout, var_name, "proj4", proj)
  ncatt_put(ncout, 0, "date", as.character(Sys.time()))
  ncatt_put(ncout, 0, "created_by", "regrid development R function CALIOPE-urbanR")
  nc_close(ncout)
  return(regular)
}
