




%%%%%%%%%%% DBSCAN %%%%%%%%%%%%%%%
function [dbcolor] = dbscan_alg(eps, MinPts, eps2);
global DISTM;
global X;
% global L;
global N;
global D;

%	eps=55; MinPts=80; eps2=30;
	dbcolor = zeros(N,1);
	rdbs=0;
	ccolor=0;
	NUM_COLORS=0;
	
	eps_round=0;
	MEP=10000;
	
while (rdbs<2000000)
	disp('==============================================');
	rdbs=rdbs+1
	
	ind_eps_round = find(dbcolor<=MEP*eps_round);
	ll = length(ind_eps_round)
	% if (ll<1)
	% 	ind_not_colored = find(mod(dbcolor,MEP)==0);
	% 	pts_not_colored  = length(ind_not_colored)
	% 	if (length(ind_not_colored)>N/4)
	% 		eps_round=eps_round+1
	% 		eps = eps * 1.3
	% 		pause;
	% 	else
	% 		break;
	% 	end;
	% end;
	
	
	queue = zeros(N,1);
	% que_inq = zeros(N,1);
	qb=-1; qe=-1; 
	

	% find a starting point
	lli = randperm(ll);
	pts=-1;
	% pause
	for t=ind_eps_round(lli)'
		ind = find (DISTM(t,:)<eps);
		pts = length(ind);
		if(pts<MinPts)
			pts=-1;
			dbcolor(t)=dbcolor(t) + MEP;
			continue;
		end;
		break;		
	end	

	if (pts<0) %% cant start the queue...
		ind_not_colored = find(mod(dbcolor,MEP)==0);
		pts_not_colored  = length(ind_not_colored)
		disp('cant start the queue...adjust eps?') 
		if (length(ind_not_colored)>N)
			eps_round=eps_round+1
			eps = eps * 1.3
			pause;
			continue;
		else	
			break;
		end; 
	end
	
	% set up start queue, and current_color
	t
	queue(1)=t; 
	qb=1; qe=1; 
	ccolor = mod( dbcolor(t), MEP);
	if(ccolor==0) 
		NUM_COLORS = NUM_COLORS+1;
		ccolor = NUM_COLORS;
	end;
	dbcolor(t)= MEP*eps_round + ccolor;
	ccolor
	dbcolor_t = dbcolor(t)
	
	while (qb<=qe)
		
		t = queue(qb)		
		ind = find (DISTM(t,:)<eps);
		pts = length(ind)
		if(pts>=MinPts)			
	
			%no_added_= length(ind);
			%L(ind)' 
			
			%% find points in the neighborhood of t
			i1  = find(DISTM(t,ind)<eps2);
			ind = ind(i1);
			pts1 = length(ind)
		
			%% find points in the neighboorhood current_color prev rounds
			%i2 = find(mod (dbcolor(ind), MEP) == ccolor );
			
			%% find points uncolored yet in the neighboorhood
			i3 = find(mod(dbcolor(ind),MEP)==0 );
			ind = ind(i3);
			 
			%% color the points 
			dbcolor(ind) = MEP*eps_round + ccolor;
			pts2 = length(ind)
			
			% colored_ccolor = length(find(dbcolor==ccolor))
			%% add new colored points to queue
			queue(qe+1: qe+pts2) = ind;
			qb
			qe = qe+pts2
			%pause
		end;
		qb = qb+1; 
	end;
	
	if (qe>1)
		[hc, edges] = histcounts(mod(dbcolor,MEP),NUM_COLORS+1);
		hc
		pause;
	end;
end; 
dbcolor = mod(dbcolor,MEP);
[hc, edges] = histcounts(dbcolor,NUM_COLORS+1);
hc
rdbs

return;






 
