library(stockassessment)

oldwd<-setwd("data")
cn<-read.ices("cn.dat")
cw<-read.ices("cw.dat")
dw<-read.ices("dw.dat")
lw<-read.ices("lw.dat")
mo<-read.ices("mo.dat")
nm<-read.ices("nm.dat")
pf<-read.ices("pf.dat")
pm<-read.ices("pm.dat")
sw<-read.ices("sw.dat")
surveys<-read.ices("survey.dat")

cv1<-read.ices("survey-haddock-Q1-1-8plus_CV.dat")
attr(surveys[[1]],"weight")<-1/log(cv1^2+1)

cv2<-read.ices("survey-haddock-Q3Q4-0-8plus_CV.dat")
attr(surveys[[2]],"weight")<-1/log(cv2^2+1)

land.no<-read.ices("lf.dat")
dis.no<-read.ices("nor_had_cn_dis.txt")


# Modify to 8+ data
cutage<-8
low<-0
GE<-which(as.numeric(colnames(cn))>=cutage)
E<-which(as.numeric(colnames(cn))==cutage)
w<-cn[,GE]/rowSums(cn[,GE])
wex<-rbind(w,w[nrow(w),])
wD<-dis.no[,GE]/ifelse(rowSums(dis.no[,GE])>0,rowSums(dis.no[,GE]),1)
wL<-land.no[,GE]/rowSums(land.no[,GE])
cn[,E]<-rowSums(cn[,GE])
cn<-cn[,low:E]
mo[,E]<-rowSums(mo[,GE]*wex)
mo<-mo[,low:E]
sw[,E]<-rowSums(sw[,GE]*wex)
sw<-sw[,low:E]
cw[,E]<-rowSums(cw[,GE]*w)
cw<-cw[,low:E]
dw[,E]<-rowSums(dw[,GE]*wD)
dw<-dw[,low:E]
lw[,E]<-rowSums(lw[,GE]*wL)
lw<-lw[,low:E]
nm[,E]<-rowSums(nm[,GE]*wex)
nm<-nm[,low:E]
land.no[,E]<-rowSums(land.no[,GE])
land.no<-land.no[,low:E]
lf<-ifelse(cn>0,land.no/cn,1)
pf<-pf[,low:E]
pm<-pm[,low:E]





setwd(oldwd)

dat<-setup.sam.data(surveys=surveys,
                    residual.fleet=cn, 
                    prop.mature=mo, 
                    stock.mean.weight=sw, 
                    catch.mean.weight=cw, 
                    dis.mean.weight=dw, 
                    land.mean.weight=lw,
                    prop.f=pf, 
                    prop.m=pm, 
                    natural.mortality=nm, 
                    land.frac=lf)

dat<-reduce(dat, year=c(1965:1971))
save(dat, file="run/data.RData")
