# Small script intended to replace 'make' for running SAM 
# locally on computers without 
#
# Anders Nielsen <anders@nielsensweb.org> Nov. 2012. 

#set path to this file
sam.home<-getwd()
homeOK<-file.exists(paste(sam.home,'make.R', sep='/'))
if(homeOK){
  setwd(sam.home)
  cat('\n This is a small R-script, which allows you to run and plot results from the state-space assessment model.\n\n')
  cat('\nTo get started try typing:\n\n')
  cat('\tmake.clean()\n')
  cat('\tmake.data()\n')
  cat('\tmake.compile()\n')
  cat('\tmake.run()\n')
  cat('\tmake.lo()\n')
  cat('\tmake.retro()\n')
  cat('\tmake.updateBase()\n')
  cat('\tmake.plot()\n')
  cat('\tmake.view()\n\n')
  cat('Then find graphs and tables in the "res" folder \n')
}else{
  stop('\nIt seems the path for sam.home is not set correctly. \n\nTry sourcing with the "chdir=TRUE" option e.g. like:: \n\n   source("c:/path/to/file/make.R", chdir=TRUE)\n\n')
}

make.clean<-function(){
  setwd(paste(sam.home,'/baserun',sep=''))
  unlink(dir())  
  setwd(paste(sam.home,'/run',sep=''))
  unlink(dir())  
  setwd(paste(sam.home,'/res',sep=''))
  unlink(dir())
  setwd(paste(sam.home,'/RETRO',sep=''))
  unlink(dir(), recursive = TRUE)
  setwd(paste(sam.home,'/LO',sep=''))
  unlink(dir(), recursive = TRUE)
  setwd(sam.home)  
}

make.compile<-function(){
  setwd(paste(sam.home,'/run',sep=''))
  file.copy('../src/sam.tpl','sam.tpl',overwrite=TRUE)
  file.copy('../src/nLogNormal.h','nLogNormal.h',overwrite=TRUE)
  system('admb -rs sam')
  setwd(sam.home)
}

make.data<-function(){
  setwd(sam.home)
  source('src/datascript.R')
  setwd(paste(sam.home,'/run',sep=''))
  system('./sam -datatestonly > ../log/data.out')
  setwd(sam.home)
  source('src/datavalidator.R')
  compareclone('run/sam.dat','run/dataclone.log')
  setwd(sam.home)
}

make.run<-function(){
  setwd(sam.home)
  make.data()
  file.copy(paste('conf/', dir('conf'), sep='/'),'run',overwrite=TRUE)
  setwd(paste(sam.home,'/run',sep=''))
  system('./sam -nr 2 -noinit -iprint 1')
  setwd(sam.home)
}

make.updateBase<-function(){
  setwd(sam.home)
  unlink('baserun', recursive = TRUE)
  dir.create('baserun')
  setwd(paste(sam.home,'/run',sep=''))  
  file.copy(dir(),'../baserun/')
  setwd(sam.home)  
}

make.plot<-function(){
  setwd(sam.home)
  source('src/plotscript.R')
  setwd(sam.home)  
}

make.retro<-function(){
  setwd(sam.home)
  source('src/common.R')
  ##
  if (.Platform$OS.type == "windows") {
    unlink('RETRO', recursive = TRUE)
    dir.create('RETRO')
    setwd(paste(sam.home,'/run',sep=''))  
    filelist<-dir()
    for(f in filelist){
      file.copy(f,paste('../RETRO/',f,sep=''))
    }
    setwd('../RETRO')
  }else{
    system('cp -r run/* RETRO')
    setwd('RETRO')
  }
  filen<-textConnection(gsub("^[[:blank:]]*#.*","",readLines("../conf/retro.cfg")))  
  ret.tab<-read.table(filen,header=FALSE)
  #ret.tab<-read.table('../conf/retro.cfg')
  RETRO<-list()
  for(i in 1:nrow(ret.tab)){
    cat(paste('Now running ',i,' out of ', nrow(ret.tab), ' retrospective runs.\n', sep=''), file='header.txt')
    red <- as.numeric(ret.tab[i,])
    cat(red,"\n",file='reduced.cfg')
    file.copy('sam.par','sam.pin', overwrite=TRUE)
    system('./sam -nr 2 -noinit -iprint 1')
    RETRO[[i]]<-read.fit('sam')[c('years','fbar','ssb','R')]
    file.copy("../run/sam.par","sam.par",TRUE);
  }
  setwd(paste(sam.home,'/run',sep=''))
  save(RETRO,file='RETRO.RData')
  setwd(sam.home)
}

make.lo<-function(){
  setwd(sam.home)
  source('src/common.R')

  if (.Platform$OS.type == "windows") {
    unlink('LO', recursive = TRUE)
    dir.create('LO')
    setwd(paste(sam.home,'/run',sep=''))  
    filelist<-dir()
    for(f in filelist){
      file.copy(f,paste('../LO/',f,sep=''))
    }
    setwd('../LO')
  }else{
    system('cp -r run/* LO')
    setwd('LO')
  }
  filen<-textConnection(gsub("^[[:blank:]]*#.*","",readLines("../conf/leaveout.cfg")))  
  ret.tab<-read.table(filen,header=FALSE)
  LO<-list();
  for(i in 1:nrow(ret.tab)){
    cat(paste('Now running ',i,' out of ', nrow(ret.tab), ' leave-one-out runs.\n', sep=''), file='header.txt')
    red <- as.numeric(ret.tab[i,])
    cat(red,"\n",file='reduced.cfg')
    file.copy('sam.par','sam.pin', overwrite=TRUE)
    system('./sam -nr 2 -noinit -iprint 1')
    fit<-read.fit('sam') 
    #fit$civec<-civec(fit)  
    LO[[i]]<-fit[c('years','fbar','ssb','R')]
    file.copy("../run/sam.par","sam.par",TRUE);
  }
  setwd(paste(sam.home,'/run',sep=''))
  save(LO,file='LO.RData')
  setwd(sam.home)
}

make.view<-function(){
  setwd(sam.home)
  snips<-list(
    c("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\"> ", 
      "<html>", "<head>", "<title>Stock Assessment</title>", "</head>", 
      "<body>", "<table class=\"banner\">", "      <col class=\"col1\"/> <col class=\"col2\"/>", 
      "     <tr> <td> <a href=\"index.php\"><img alt=\"\" src=\"http://130.226.135.24/NScod/images/Gartoon-Bluefish-icon.png\"></a> </td>", 
      "       <td align=\"center\"> <h1> Stockassessment.org </h1> </td></tr>", 
      "</table>", "<table class=\"content\">"), 
    c("  <tr><td width=\"50%\" class=\"graphTitle\"><br/></td>", 
      "      <td width=\"50%\" class=\"graphTitle\"><br/></td></tr>", 
      "  <tr><td width=\"50%\" class=\"graph\" > <a href=\"big_fig1\"><img alt=\"Click to enlarge\" src=\"fig1\"></a> </td> ", 
      "      <td width=\"50%\" class=\"graph\" > <a href=\"big_fig2\"><img alt=\"Click to enlarge\" src=\"fig2\"></a> </td> </tr>", 
      "  <tr><td width=\"50%\" class=\"graphCaption\"> <br/></td>", 
      "      <td width=\"50%\" class=\"graphCaption\"> <br/></td></tr>"), 
    c("  <tr><td width=\"50%\" class=\"graphTitle\"><br/></td></tr>", 
      "  <tr><td width=\"50%\" class=\"graph\" > <a href=\"big_fig1\"><img alt=\"Click to enlarge\" src=\"fig1\"></a> </td> </tr>", 
      "  <tr><td width=\"50%\" class=\"graphCaption\"> <br/></td></tr>"), 
    "</table>", 
    c(" </body>", "</html>")
  )
  flist<-dir('res', pattern='png$')
  flist<-flist[grep('^(?!big).+', flist, perl=TRUE)]
  nfiles<-length(flist)
  res<-list()
  rescount<-1
  res[[rescount]]<-snips[1]
  for(i in 1:(nfiles%/%2)){
    s<-snips[[2]]
    s<-gsub('fig1',flist[2*i-1],s)
    s<-gsub('fig2',flist[2*i],s)
    rescount<-rescount+1
    res[[rescount]]<-s
  }
  if((nfiles%%2)!=0){
    s<-snips[[3]]
    s<-gsub('fig1',flist[nfiles],s)
    rescount<-rescount+1
    res[[rescount]]<-s
  }
  rescount<-rescount+1
  res[[rescount]]<-snips[[4]]
  rescount<-rescount+1
  res[[rescount]]<-snips[[5]]
  flist<-dir('res', pattern='html$')
  flist<-flist[flist!='view.html']
  for(f in flist){
    s<-readLines(paste('res/',f,sep=''))
    rescount<-rescount+1
    res[[rescount]]<-s
  }
  writeLines(unlist(res), con='res/view.html')
  browseURL('res/view.html')
  setwd(sam.home)
}

make.all<-function(){
  make.data()
  make.compile()
  make.run()
  make.updateBase()
  make.plot()
}