function [ind,res,deg,mni,mxi]=approxeq(x,ref,tol)

%ind=approxeq(x,ref);
%[ind,res,deg,mni,mxi]=approxeq(x,ref,tol);
%
%function to find index where a vector is most nearly equal
%to the entered reference value.  The process is done through
%minimization.  If there is a degenerate set satisfying the
%minimization condition, the function will report the central
%indice of the degenerate set.
%
%tol specifies a tolerance limit
%ind gives the index
%res gives the residual
%deg gives the level of degeneracy 
%mni gives the minimum index
%mxi gives the maximum index

if nargin<3, tol=inf; end;

if any(size(x)==1), x=x(:); end;

[M,N]=size(x);
res=nan*ones(1,N);
ind=nan*ones(1,N);
deg=nan*ones(1,N);
mni=nan*ones(1,N);
mxi=nan*ones(1,N);

%%%%% do 1st loop to find the minimum, which may be degenerate
for i=1:N
absdiff=abs(x(:,i)-ref);
absdiff(find(isnan(absdiff)))=inf*ones(size(find(isnan(absdiff))));
[res(i)]=min(absdiff);
end; %for loop

%%%%% now do a 2nd pass to find the degenerate set
for j=1:N
absdiff=abs(x(:,j)-ref);
indp2=find(flpteq(absdiff,res(j)));
deg(j)=length(indp2);
%%%%% now find the central element of the degenerate set
if rem(length(indp2),2), ind(j)=median(indp2);
else,  ind(j)=median(indp2(1:length(indp2)-1));
end;
mni(j)=min(indp2);
mxi(j)=max(indp2);

%%%%% check for the special cases
if ind(j)==0, ind(j)=1; end;
if ind(j)>M,  ind(j)=M; end;
end; %for j loop

ind(find(abs(diag(x(ind,:))-ref)>tol))=nan;
mni(find(abs(diag(x(mni,:))-ref)>tol))=nan;
mxi(find(abs(diag(x(mxi,:))-ref)>tol))=nan;
