%Function used to localize the hippocampus inside an optimization method.
%It calls evaluate_model which is a compiled mex file. Parameters are:
%set of particles to be evaluated (SwarmR), image of the hippocampus
%(target), model parameters (outer_shift, min_bounds, max_bounds,
%best_template), penalty factors (pen)

function V = de_find(SwarmR, target, outer_shift, min_bounds, max_bounds, best_template, pen)
    persistent img;
    persistent outer_shift_cart;
    persistent template;
    persistent lb;
    persistent ub;
    persistent penalties;
    if nargin > 1 %init
        outer_shift_cart = outer_shift;
        img = target;
        template = best_template;
        lb = min_bounds;
        ub = max_bounds;
        penalties = pen;
    else %evaluate
       [SwarmSize, d1] = size(SwarmR);
       appD = zeros(SwarmSize,1);
       for q=1:SwarmSize
           appD(q) = evaluate_model(img,SwarmR(q,:),lb,ub,template,ceil(outer_shift_cart),penalties);
       end
       V = -appD; % minus because we want to minimize
    end
end

