function locmin = calcLocMin2(N,xloc,low,high)

% LOCMIN = CALCLOCMIN(N,XLOC,LOW,HIGH)
% Given a bimodal distribution (N,XLOC), this function finds the local
% minimum value that separates the two modes; it locates the local minimum
% between the two in the range bounded by two values: LOW and HIGH

% ---------------------------------
% Kyle E. Fitch, Maj, USAF (AFIT/CI)
% University of Utah
% Salt Lake City, Utah
% kyle.fitch@us.af.mil
% ---------------------------------

% Dependencies:
% None

% assumes bimodal dist. is between low and high (usually 0 and 2)
xrange = find(xloc < high & xloc > low);

% interpolate for better resolution
xq = linspace(xloc(xrange(1)),xloc(xrange(end)),1e5);
Nq = interp1(xloc,N,xq,'spline');

% find the number of extrema; should be 2 max and 1 min for bimodal
maxcount = length(find(islocalmax(Nq)==1));
mincount = length(find(islocalmin(Nq)==1));

% make sure bimodal isn't high
if xq(islocalmin(Nq)==1) > 0.75 
    mincount = 0;
end

% first check if bimodal (or more modes is fine, too)
if maxcount==2 && mincount==1
    locmin = xq(islocalmin(Nq)==1); % locate local min
elseif maxcount > 2 || mincount > 1
    disp('more than 2 modes') % not bimodal
    locmin = xq(islocalmin(Nq)==1);
    locmin = locmin(min(Nq(islocalmin(Nq)==1))==Nq(islocalmin(Nq)==1));
else
    disp('not bimodal') % not bimodal
    locmin = nan;
end
