## source('tools.R')
library(R2admb)  ## requires 0.7.2
sessionInfo()
file.copy('../DATA/theta.dat', './theta.dat',overwrite=TRUE)
system('admb -r theta')
time<-system.time(system('./theta -noinit'))
time <- unname(time["elapsed"]);

fit<-read_pars('theta')
clean_admb('theta')

idx<-c("logTheta","logr0","K","logSdU","logSdy");
coef=fit$coefficients[idx]
sd=fit$se[idx]
ci.q=coef+sd%o%c(-2,
  2)
obj=-fit$loglik
maxgrad=fit$maxgrad
ev <- try(eigen(solve(fit$vcov[idx,idx]))$value)
eratio <- if (inherits(ev,"try-error")) NA else min(ev)/max(ev)

## random effects stuff
idx = 6:205;
rcoef <- fit$coefficients[idx]
sd.r <- fit$se[idx];

results <- list(obj=obj,                     ## negative log L
                coef=coef,                   ## coefficients (MLE/mode)

                coef.median=NULL,
                sd=sd,                       ## standard deviations
                confint.quad=ci.q,           ## Nx2 - matrix 95% ci
                confint.profile=NULL,
                confint.mcmc=NULL,           ## 0.025 0.975 quantiles
                time=c(fit=time,profile=NULL),
                terminfo=c(maxgrad=maxgrad,eratio=eratio), ## MLE termination info
                convinfo=NULL,
                rcoef=rcoef,
                sd.r=sd.r
                )

save("results",file="fit.RData")

rmlist<-c("admodel.cov","admodel.hes","admodel.dep","fmin.log",
          "eigv.rpt","variance",paste('theta',c(".bar",".cpp",
          ".eva",".log", ".htp",".o","",".cor",".par",".std",
          ".dat"),sep=""))
file.remove(rmlist)

