# Removing any old data
rm(list = ls());

XsimName     = 'Xsim.csv';
XwtrQltyName = 'XwtrQlty.csv';
ySimName     = 'ySim.csv';

# Loading Xsim data and averaging the input
Xsim     = as.matrix(read.csv(XsimName,     header=TRUE));
XwtrQlty = as.matrix(read.csv(XwtrQltyName, header=TRUE));
if (nrow(Xsim) == 30) {
  # Lodaing the saved ANnet Object and the ANnet Simulation routine
  load("netDESE.RData");
  load("netTOTN.RData");
  load("netTOTP.RData");
  source("ANnet-Simulate.R");
  Xsim     = matrix(colMeans(Xsim),     nrow=1, ncol=ncol(Xsim));
  XwtrQlty = matrix(colMeans(XwtrQlty), nrow=1, ncol=ncol(XwtrQlty));
  
  # Performing the simulations
  ySim1 = fSim(netDESE, Xsim,     BiasFactor = 0.0); #FLOW
  XwtrQlty = as.matrix(cbind(ySim1, XwtrQlty));
  XTOTN = matrix(XwtrQlty[1, 1:6], nrow=1, ncol=6);
  XTOTP = matrix(XwtrQlty[1, c(1:2,7:10)], nrow=1, ncol=6);
  yTOTN = fSim(netTOTN, XTOTN, BiasFactor = 0.0); #TOTN
  yTOTP = fSim(netTOTP, XTOTP, BiasFactor = 0.0); #TOTP
  ySim2 = 0.43 * yTOTN; #ORGN
  ySim3 = 0.10 * yTOTN; #NH4
  ySim4 = 0.02 * yTOTN; #NO2
  ySim5 = 0.44 * yTOTN; #NO3
  ySim6 = 0.83 * yTOTP; #ORGP
  ySim7 = 0.17 * yTOTP; #MINP
  ySim8 = 0.; #BOD
  ySim9 = 0.; #DO
  
  # Saving the data
  ySim = cbind(ySim1,ySim2,ySim3,ySim4,ySim5,ySim6,ySim7,ySim8,ySim9);
  # ySim = cbind(0.,0.,0.,0.,0.,0.,0.,0.,0.);
  write.csv(ySim, file=ySimName, row.names=FALSE);
  
  # Updating Xsim.csv and XwtrQlty.csv to receive new input from SWAT
  Xsim     = read.csv(XsimName,     header=TRUE);
  XwtrQlty = read.csv(XwtrQltyName, header=TRUE);
  Xsim     = Xsim[-(1:7),];
  XwtrQlty = XwtrQlty[-(1:7),];
  write.csv(Xsim,     file=XsimName,     row.names=FALSE)
  write.csv(XwtrQlty, file=XwtrQltyName, row.names=FALSE)
}
