function nll = nllGR(data, parms, ierr)
% errGR computes neg log likelihood for models of algal growth rate in response
% to changes in temperature, pH and nutrients.  The actual rate predictions
% are calculated in a separate function, aGR3.m
%
% ierr controls the error model:
%    ierr = 1 SSE
%    ierr = 2 SAE
%
% priors are included on death rates (to avoid letting this response
% confuse itself with growth), K (to avoid `flipping' the type II) and
% upper thermal treshold
%   
% This is a cleaned-up and commented version of the original code,
% written by James Powell, USU, in May 2023
%
% parameters are more completely described in the script Scened_GR.m, which
% does the optimization and analysis
%
b1=parms(1); b2=parms(2); b3=parms(3); 
K=abs(parms(4)); 
c2=parms(5); c3=parms(6); 
d0=parms(7); d1=parms(8); d2=parms(9); d3=parms(10); 
sig=abs(parms(11)); % variance parameter for whichever error model

T=data(:,1);   % first row is temperature
P=data(:,2);   % second row is pH
Du=data(:,3);  % nutrients (Dust) provided

prior=1/K^2+0.0001/d1^2+0.0001/d2^2; 
sse=sum( .5*((aGR3(T,P,Du,parms) - (data(:,4))).^2)/sig^2 +.5*log(2*pi*sig^2) );
sae=sum( sqrt((aGR3(T,P,Du,parms) - (data(:,4))).^2)/sig + log(2*sig) );

nll=(ierr==1)*sse+(ierr==2)*sae+ prior; 

end

