# load required libraries
library(ncdf4)
library(ggplot2)
library(reticulate)
library(grid)
library(gridExtra)
library(car)

#load data
load("NorthAfrica_em.RData")
load("NorthAfrica_od.RData")
load("NorthAfrica_mc.RData")
load("NorthAfrica_rc.RData")
load("NorthAfrica_ustar.RData")
load("NorthAfrica_ustt3.RData")
load("NorthAfrica_ustt4.RData")


#here we transform the threshold used by the model u*t to u*tsd (for smooth and dry surface)
#to do so we divide the ustt by the moisture and rougness correction outputed by the model

NorthAfrica_usttsd3 <- matrix(0,length(NorthAfrica_ustar[,1]),length(NorthAfrica_ustar[1,]))
NorthAfrica_usttsd4 <- matrix(0,length(NorthAfrica_ustar[,1]),length(NorthAfrica_ustar[1,]))
for (d in 1:length(NorthAfrica_ustar[,1]))
{
  for (s in 1:length(NorthAfrica_ustar[1,]))
  {
    NorthAfrica_usttsd3[d,s] <- (NorthAfrica_ustt3[d,s])/(NorthAfrica_mc[d,s]*NorthAfrica_rc[d,s])
    NorthAfrica_usttsd4[d,s] <- (NorthAfrica_ustt4[d,s])/(NorthAfrica_mc[d,s]*NorthAfrica_rc[d,s])
  }
}

#save u*tsd for bin 3 and 4
save(NorthAfrica_usttsd3, file = "NorthAfrica_usttsd3.RData")
save(NorthAfrica_usttsd4, file = "NorthAfrica_usttsd4.RData")


#here u* values are transformed to u*sd
NorthAfrica_ustarsd <- matrix(0,length(NorthAfrica_ustar[,1]),length(NorthAfrica_ustar[1,]))
for (d in 1:length(NorthAfrica_ustar[,1]))
{
  for (s in 1:length(NorthAfrica_ustar[1,]))
  {
    NorthAfrica_ustarsd[d,s] <- (NorthAfrica_ustar[d,s])/(NorthAfrica_mc[d,s]*NorthAfrica_rc[d,s])
  }
}
save(NorthAfrica_ustarsd, file = "NorthAfrica_ustarsd.RData")


#saves dod/emissions and u* at 12 utc in csv format for later use in the fitting method scripts
vectorod <- c((as.vector(NorthAfrica_od[seq(4,2924,by=8),])))
vectorem <- c((as.vector(NorthAfrica_em[seq(4,2924,by=8),])))
vectorwind <-  c((as.vector(NorthAfrica_ustar[seq(4,2924,by=8),])))
vectorod <- vectorod*0.31
vectorem <- vectorem*0.31

write.csv(vectorod, file = "vectorod.csv")
write.csv(vectorem, file = "vectorem.csv")
write.csv(vectorwind, file = "vectorwind.csv")