function CAM = getcam(de)
% The Central Age Model

% Requires 2 cols of De with errors
%de=delist; %name of the data in workspace
sigma_b=0.10; %overdispersion to be added ------PROBLEM HERE------

dat=[log(de(:,1)); de(:,2)./de(:,1)]; % format data into 1 vector, need for passing to mle

% mle: alpha sets the confidence interval e.g. 0.05 for 95%
[ests ci68]=mle(dat,'nloglf',@neglogCAM,'start',sigma_b,'alpha',0.32); % use mle to find sigma
w=1./(ests^2+(de(:,2)./de(:,1)).^2); %the weights
cen_age=exp(sum(w.*log(de(:,1)))/sum(w)); %the central age
cen_err=sum(w)^-0.5;
OD=ests;
OD_err=(2*OD^2*sum(w.^2))^-0.5;

CAM=[cen_age cen_err OD OD_err];
end

function L0 = neglogCAM(param,dat,cens,freq)
%the negative log likelihood function for the central age model

n=length(dat)/2;
yu=dat(1:n,1);
su=dat(n+1:2*n);
sigma_b=param;
%negloglik
wu=1./(sigma_b^2 + su.^2);
rwu=sqrt(wu);

mu0=sum(wu.*yu)/sum(wu);
fu0=rwu.*exp(-0.5*wu.*(yu-mu0).^2);
L0=-sum(log((1/sqrt(2*pi)).*fu0));
end