function [nearestneighbor] = findNearestNeighbor(vector,value)

% small function to find the indices of the neighboring values
% that would surround 'value'
% 31july98, HDH.
% INPUT: vector - the vector of values in which one hopes to find neighbors,
%        value - the value for which one wishes to find neighbors,
% OUTPUT: smallneighbor - the neighbor value just less than the 'value',
%         bigneighbor - the neighbor value just greater than the 'value'.
% 09 January 2010, HHF. Modified to return nearest neighbor.


diffs = vector - value;
diffs = diffs(:);
% need to find the two smallest diffs, pos and neg.
[a,b] = find(diffs<0);
[c,d] = find(diffs>=0);
maxneg = max(diffs(a));
minpos = min(diffs(c));
if isempty(maxneg) % no value in 'vector' less than 'value'
    nearestneighbor= vector(1);
elseif isempty(minpos)  % no value in 'vector' greater than 'value'
    nearestneighbor= vector(end);
else % 'value' is in middle of 'vector'
    smallneighbor = vector(find(diffs==maxneg));
    bigneighbor = vector(find(diffs==minpos));

    if abs(value-smallneighbor) < abs(value-bigneighbor)
        nearestneighbor = smallneighbor;
    else
        nearestneighbor = bigneighbor;
    end
end