function Ind=htm_search_point(HTM,Coo)
% Search for a single point-like coordinate in an HTM tree
% Package: celestial.htm
% Description: Search for a single point-like coordinate in an HTM tree.
% Input  : - HTM tree as generated by htm_build.m
%          - [Long, Lat] in radians or [X,Y,Z] cosine direction of
%            a single point to search in the HTM.
% Output : - Index of the leaf in the HTM in which the search point is
%            contained.
% Tested : Matlab 7.11
%     By : Eran O. Ofek                    Jul 2014
%    URL : http://weizmann.ac.il/home/eofek/matlab/
% Example: [HTM,LevList]=celestial.htm.htm_build(7);
%          I=celestial.htm.htm_search_point(HTM,[1,1])
% Reliable: 2
%--------------------------------------------------------------------------

if (size(Coo,2)==2)
    CD = celestial.coo.cosined(Coo);
    %[CD1,CD2,CD3]=coo2cosined(Coo(:,1),Coo(:,2));
    %CD = [CD1, CD2, CD3];
else
    CD = Coo;
end

% check first level:
Cont = true;
Ind = zeros(1,1);
while Cont
    Ind = Ind + 1;
    Flag = celestial.htm.in_polysphere(CD,HTM(Ind).cosd);
    Cont = ~Flag;
    if (Ind>8)
        error('Can not find position within first level');
    end
end
% I is the index of the level to search
Cont = true;

%Flag = false(4,1);
while Cont
    
    if (isempty(HTM(Ind).son))
        % reached a leaf
        Cont = false;
    else
        
        Flag = false;
        I = 0;
        while ~Flag
            I = I + 1;
            Flag = celestial.htm.in_polysphere(CD,HTM(HTM(Ind).son(I)).cosd);
        end
        Ind = HTM(Ind).son(I);
           
%         Flag(1) = in_polysphere(CD,HTM(HTM(Ind).son(1)).cosd);
%         Flag(2) = in_polysphere(CD,HTM(HTM(Ind).son(2)).cosd);
%         Flag(3) = in_polysphere(CD,HTM(HTM(Ind).son(3)).cosd);
%         Flag(4) = in_polysphere(CD,HTM(HTM(Ind).son(4)).cosd);
%     
%         Ind = HTM(Ind).son(Flag);
         
    end
end

