library(stockassessment)
setwd("run")
load("data.RData")
conf<-loadConf(dat,"../conf/model.cfg", patch=TRUE)
par<-defpar(dat,conf)
fit <- sam.fit(dat,conf,par)


Ntable<-ntable(fit)
Ftab<-faytable(fit)
maxyear<-max(as.integer(rownames(Ftab)))
yrrange<-1984:(maxyear-1)
yridx<-rownames(Ntable)%in%yrrange
con<-cnW-cnWO
con<-con[rownames(con)%in%yrrange,1:5]
oldN7<-Ntable[as.integer(rownames(Ntable))>=1984,1:5]
checkN<-oldN7
oldN7[1:(nrow(oldN7)-1),1:4]<-NA
oldM<-fit$data$natMor[yridx,1:5]
oldF<-Ftab[yridx,1:5]
Z<-fit$data$natMor+Ftab
modelC<-Ftab/Z*(1-exp(-Z))*Ntable
modelC<-modelC[rownames(modelC)%in%yrrange,1:4] 

N7<-oldN7
minAgem1<-3-1
minYearm1<-1984-1
for(y in (maxyear-1):1984){
  for(a in 6:3){  
    N7[y-minYearm1,a-minAgem1]<-N7[y+1-minYearm1,a+1-minAgem1]*exp(oldM[y-minYearm1,a-minAgem1])+
                                  modelC[y-minYearm1,a-minAgem1]*exp(0.5*oldM[y-minYearm1,a-minAgem1])+
                                  con[y-minYearm1,a-minAgem1]*exp(0.5*oldM[y-minYearm1,a-minAgem1])
  }
}

MM<-oldF*0
for(y in (maxyear-1):1984){
  for(a in 6:3){  
    MM[y-minYearm1,a-minAgem1]<-log(N7[y-minYearm1,a-minAgem1]/N7[y+1-minYearm1,a+1-minAgem1])-oldF[y-minYearm1,a-minAgem1]-oldM[y-minYearm1,a-minAgem1]
  }
}

MM[MM<0]<-0
MM<-MM

aveMM<-colMeans(MM)
newM<-fit$data$natMor
ridx<-rownames(newM)%in%rownames(MM)
cidx<-colnames(newM)%in%colnames(MM)

newM[ridx,cidx]<- MM+.2
for(i in which(!ridx)){
  newM[i,cidx]<- aveMM+.2
}

newM[nrow(newM),] <- newM[nrow(newM)-1,] 

oldfit<-fit


dat<-fit$data
dat$natMor=newM

fit <- sam.fit(dat,conf,par)

save(fit, con, file="model.RData")


