function x = binary_search(a, y, nhi, nlo)
% binary_search(a, y, nhi, nlo)
%	Recursive. Returns index of the element of y that would come after element 'a' in 
%	the list, if element 'a' were in the list (i.e. if element 'a' were greater than 
%	y(nlo) and less than y(nhi), binary_search returns nhi).
%		If the argument 'a' is equal to an element y(i), then the function returns i.
%	If the argument 'a' is out of the range of y, then the function returns 1 and an
%	error message.

% ARGUMENTS:
%				a		value whose index we are searching for
%				y		array, the list that we are searching (must be in ascending order)
%				nhi	uppermost index of y
%				nlo	lowermost index of y (e.g. 1, if we are searching the whole array)
% INPUT FILES:	none
% CALLS:			none
% CALLED BY:	lin_interp

if (nhi - nlo) == 1 % & ((a > x(n_high)) & a < x(n_low)) calling fn determines this
   x = nhi;		% end of search
   return   
end

nmid = nlo;
% We need to make sure that the indices are integer:
if mod( nhi - nmid, 2 ) ~= 0
   nmid = nhi - (nhi - nlo + 1)/2;
else
   nmid = nhi - (nhi - nlo)/2;
end

if (a > y(nmid)) & (a < y(nhi))
   x = binary_search(a, y, nhi, nmid);
elseif (a > y(nlo)) & (a < y(nmid))
   x = binary_search(a, y, nmid, nlo);
elseif a == y(nhi)
   x = nhi;
elseif a == y(nlo)
   x = nlo;
elseif a == y(nmid)
   x = nmid;
else
   disp('BINARY_SEARCH.M: Error, search element is out of bounds');
   x = 1;
   return
end

   