library(stockassessment)
library(TMB)


procresfix <- function(fit, map = fit$obj$env$map, ...){
  pp<-fit$pl
  attr(pp,"what") <- NULL
  pp$missing <- NULL
  fakefile <- file()
  sink(fakefile)
  saveConf(fit$conf, file="")
  sink()
  conf <- loadConf(fit$data, fakefile, patch=TRUE)
  close(fakefile)
  fit.co<-sam.fit(fit$data, conf, pp, run=FALSE, map = map)
  fit.co$obj$env$data$resFlag<-1
  fit.co$obj$retape()
  sdrep <- sdreport(fit.co$obj,fit$opt$par)  
  ages <- as.integer(colnames(fit.co$data$natMor))
  iF<-fit.co$conf$keyLogFsta[1,]
  if (exists(".Random.seed")){
    oldseed <- get(".Random.seed", .GlobalEnv)
    oldRNGkind <- RNGkind()
  }
  set.seed(123456)
  idx <- which(names(sdrep$value)=="resN")
  resN <- rmvnorm(1,mu=sdrep$value[idx], Sigma=sdrep$cov[idx,idx])
  resN <- matrix(resN, nrow=nrow(fit.co$pl$logN))
  resN <- data.frame(year=fit.co$data$years[as.vector(col(resN))],
                     fleet=1,
                     age=ages[as.vector(row(resN))],
                     residual=as.vector(resN))
  idx <- which(names(sdrep$value)=="resF")
  resF <- rmvnorm(1,mu=sdrep$value[idx], Sigma=sdrep$cov[idx,idx])
  resF <- matrix(resF, nrow=nrow(fit.co$pl$logF))
  resF <- data.frame(year=fit.co$data$years[as.vector(col(resF))],
                     fleet=2,
                     age=tapply(ages, INDEX=iF, FUN=mean)[as.vector(row(resF))],
                     residual=as.vector(resF))
  ret <- rbind(resN, resF)
  attr(ret, "fleetNames") <- c("Joint sample residuals log(N)", "Joint sample residuals log(F)")
  class(ret) <- "samres"
  if (exists("oldseed")){
    do.call("RNGkind",as.list(oldRNGkind))
    assign(".Random.seed", oldseed, .GlobalEnv)
  }
  return(ret)
}


load("run/model.RData")
RES<-residuals(fit)
RESP<-procresfix(fit)
save(RES, RESP, file="run/residuals.RData")