if(length(find.package("nlmixr2est", quiet = TRUE))>0){
  library(nlmixr2)
}else if(length(find.package("nlmixr", quiet = TRUE))>0){
  library(nlmixr)
}else{
  warning("You need either the 'nlmixr' or 'nlmixr2' package to run models. This step will crash\n")
}
options(keep.source = TRUE)
if(!exists("{{{data}}}", envir=.GlobalEnv)) {
  if(file.exists("{{{locproj}}}/data/{{{data}}}.rds")){
    data_nlm <- readRDS("{{{locproj}}}/data/{{{data}}}.rds")
  }else if(file.exists("{{{locproj}}}/data/{{{data}}}.csv")){
    data_nlm <- read.csv("{{{locproj}}}/data/{{{data}}}.csv")
  }
}else{
  data_nlm <- {{{data}}}
}
if("{{subs}}"!=""){
  data_nlm <- try(subset(data_nlm,{{{subs}}}))
  if(inherits(data_nlm,"try-error")) cat("!!!! subset meta data (subs) in model, results in an error, please check syntax !!!!\n")
  if(!inherits(data_nlm,"try-error") && nrow(data_nlm)==0) cat("!!!! subset meta data (subs) in model, results in an empty data frame, please check syntax !!!!\n")
}

source("{{{modelloc}}}")
setwd("{{{locproj}}}/shinyMixR/temp")
modres <- try(nlmixr2est::nlmixr({{{modelname}}}, data=data_nlm, est="{{{est}}}",control={{{control}}},table=tableControl(cwres={{{addcwres}}}, npde={{{addnpde}}})))

{{#saveres}}
if(length(class(modres))>1 && !"try-error"%in%class(modres)){
  saveRDS(modres,file="../{{{modelname}}}.res.rds")
  if(length(find.package("nlmixr2est", quiet = TRUE))>0){
    saveRDS(list(OBJF=modres$objective,CONDNR=modres$conditionNumberCor,partbl=modres$parFixedDf,partblf=modres$parFixed,omega=modres$omega,
                 tottime=rowSums(modres$time)),file="../{{{modelname}}}.ressum.rds")
  }else{
    saveRDS(list(OBJF=modres$objective,partbl=modres$popDf,partblf=modres$par.fixed,omega=modres$omega,
                 tottime=rowSums(modres$time)),file="../{{{modelname}}}.ressum.rds")
  }
}
{{/saveres}}
cat("run finished!\n")
