function whattominimise = NLLF_optall(varyparams,data,allparams,vary)
%Designed to be general
% allparams is a vector containing [n p q qsigmapercentage QVtype noise pstim offset]
% vary contains the indices of the elements in allparams which are to be varied.
% These will be replaced with the values stored in varyparams
% Eg if vary = [2 4] then varyparams must contain two elements.
% p, instead of being allparams(2), will be taken to be varyparams(1)
% qsigmapercent, instead of being allparams(4), will be taken to be varyparams(2)

% May 16th 2008. Updated at Guy Major's request to allow different possible
% fit techniques, controlled by fittype:
% fittype = 'MLE', maximum likelihood fitting, whattominimise = -log(likelihood), -sum(logPDF)
% fittype = 'GUY1', whattominimise = -sum(PDF.*logPDF)
% fittype = 'GUY2', whattominimise = -sum(PDF)

if length(allparams) ~= 12
   disp('Need 12 parameters in NLLF_optall')
   return
elseif length(varyparams) ~= length(vary)
   disp('Number of parameters to be varied does not match')
end

params = allparams;
for j=1:length(vary)
   params(vary(j)) = varyparams(j);
end

% Construct the model:
% Now test
model.n = params(1);
model.p = params(2);
model.q = params(3);
model.qsigma = params(4).*params(3)/100; % qsigmapercent expresses quantal variance as a percentage of quantal size
model.QVtype = params(5);
model.noise = params(6);
model.pstim = params(7);
model.offset = params(8);
model.glitchrate = params(9);
model.fittype = params(10);
model.glitchmin = params(11);
model.glitchmax = params(12);

PDF = BinomPDF(model,data);
if any(PDF==0)
   whattominimise = Inf;
else
   logPDF = log(PDF);
   if ~isreal(logPDF)
       'encountered negative probability - this should not happen!'
       stop
   end
   if model.fittype==1 % MLE
       whattominimise = -sum(logPDF);
   elseif model.fittype==2 %GUY1
       whattominimise = -sum(PDF.*logPDF);
   elseif model.fittype==3 %GUY2
       whattominimise = -sum(PDF);
   end
end
