#!/usr/bin/env Rscript
library(uqsa)
library(SBtabVFGEN)

# The names of the file we work with:
xlsx <- "GABAB_SBtab_new.xlsx"
cFile <- "./GABAB_signaling_gvf.c"
rFile <- "./GABAB_signaling.R"

# has the model changed since the c file was created?
dt <- difftime(file.mtime(xlsx), file.mtime(cFile))

# read the SBtab file, an excel spreadsheet in this case:
SBtab <- sbtab_from_excel(xlsx)

if (!file.exists(cFile) || dt > 0){
    m <- sbtab_to_vfgen(SBtab, cla=FALSE) #description of the model
    C <- generateCode(m) #generates C code
    R <- generateRCode(m) #generates R code
    cat(C, sep="\n", file=cFile)
    cat(R, sep="\n", file=rFile)
}

source("GABAB_signaling.R")
experiments <- sbtab.data(SBtab)

# The checkModel function checks that the model exists,
# and also whether the shared library for it already exists.
# If it doesn't, it will make one:
modelName <- checkModel("GABAB_signaling",cFile) # creates `.so`

# simulator.c returns a function: `simulate(p)`. It simulates the
# experiments, using the specified model. The returned function
# remembers which experiments and model to use (it is a closure).
# Only the parameters p are an explicit argument to `simulate`
simulate <- simulator.c(experiments, modelName)

nInput <- length(experiments[[1]]$input)
p_u <- GABAB_signaling_default()
p <- head(p_u,-nInput)

y <- simulate(p)

funcNames <- names(experiments[[1]]$outputValues)
N <- length(experiments)
M <- head(dim(y[[1]]$func),1)
#pdf(file="output.pdf")
par(mfrow=c(M,N))
for (j in seq(N)){
    for (i in seq(M)){
        plot(experiments[[j]]$outputTimes,y[[j]]$func[i,,1],ylab=funcNames[i],xlab="time (ms)",type='l')
    }
}
#dev.off()