%function addOverlap(whichMap)
% inputs:
%   whichMap: 'geo' or 'utm'
function addOverlap(whichMap)
	global fighandles, global mission
if isempty(fighandles), return, end
try,

if get(fighandles.sonar_checkbox,'Value'),

	if isfield(mission{1},'gpsfixesperleg'),
		if (mission{1}.gpsfixesperleg > 1),
			helpdlg('Please redo the mission using a gpsfixesperleg of 1 to show sonar coverage.','Sonar Checkbox Help');
			set(fighandles.sonar_checkbox,'Value',0);
			return
		end
	end
    
    [verts] = saveVerts('returnverts'); % get saved vertices of every sonar patch
    cmap = [0.6 0.6 1; 0.3 0.3 1; 0 0 .9; 0 0 .7;0 0 .5; 0 1 0; 0 .9 0; 0 .7 0; 0 .5 0; 0 .3 0; 1 0 0; 0.9 0 0; .7 0 0; .5 0 0; .3 0 0];  % colormap
    
    intsx = [];  % x intersection points
    intsy = [];  % y intersection points
	
    % initialize first patch for each leg
    for ii=1:size(verts,3),
        sonar{1}.leg{ii}.patch{1}.verts = [verts(:,1,ii),verts(:,2,ii)];
        sonar{1}.leg{ii}.patch{1}.overlaps = 1;
        patch(verts(:,1,ii),verts(:,2,ii),cmap(1,:));
    end

    % calc how far to go back on each section of survey to calc overlaps
    % if nover = 0, no overlaps, dont need to calc extra patches
    range = selectSonarRange;
    if isfield(mission{1},'trackspacing1'),
    	[nover,err] = calcOverlaps(range,mission{1}.trackspacing1,mission{1}.trackspacing2);
    else
    	nover = size(verts,3);	% always calc all patches
    end
    
    ii = 1;
    nlegs = getLegs('get',0);
    
    % for every patch, want to look at all patches that have come before it
    % if there are overlaps, add more patches (effectively splitting base trackline patch)
    
    plotoverlaps = [];
    plotintx = [];
    plotinty = [];
    hw = waitbar(0,'Please wait...','Name','Calculating, Please wait...');
    for ii=1:size(verts,3),	% ii = current trackline (TL)
        patchnum = 2; 		% next patch index - base patch for each TL is patch 1.
        if ((ii-nover) < 1), ind = 1; else, ind=ii-nover; end
        if (length(nlegs) > 1), 
        
        	if (ii > nlegs(1)), ind=1; end % criss-cross
        	if (length(nlegs) > 2),        % qroute
        		if (ii > nlegs(2)),
        			nsegs = length(nlegs);
        			seg = 1;
        			for inseg=1:nsegs,
        				if (ii > sum(nlegs(1:inseg)))
        					seg = seg + 1;
        				end
        			end
        			numlegperseg = ii - sum(nlegs(1:seg-1));
        			ind = ii - nlegs(seg) - (numlegperseg - 1);
        		end
        	end
        
        %if ii > 1, ind = ii - 1; else ind = 1; end
        end
        
        % check for overlaps
        for jj=ind:ii,		% jj = earlier trackline patch, start from first
	    if ~(ii==jj), 	% dont compare the same polygon
                for kk=1:length(sonar{1}.leg{jj}.patch),	% kk = patches for jj - compare with current TL(ii) for overlaps
                    
                    patchverts = sonar{1}.leg{jj}.patch{kk}.verts;
		    [intsx,intsy] = getIntersections(verts(:,1,ii),verts(:,2,ii),patchverts(:,1),patchverts(:,2),whichMap);
                    if ~isempty(intsx),
			% this patch overlaps - add a patch at the intersection pts, and update num overlaps
                  	if (length(intsx)>5),
                  		% try the other way
                  		[intsx,intsy] = getIntersections(patchverts(:,1),patchverts(:,2),verts(:,1,ii),verts(:,2,ii),whichMap);
                  	else
                  		lookforw = 0;
                  		while (length(intsx)<5),
					intsx(length(intsx)+1) = intsx(1+lookforw);
        				intsy(length(intsy)+1) = intsy(1+lookforw);
        				lookforw = lookforw + 1;
                  		end
                  	end
                  	if ~isempty(intsx),
               		   	if length(intsx) < size(plotintx,2),
               		   		lookforw = 0;
					while (length(intsx)<size(plotintx,2)),
						intsx(length(intsx)+1) = intsx(1+lookforw);
					        intsy(length(intsy)+1) = intsy(1+lookforw);
					        lookforw = lookforw + 1;
               		   		end
               		   	end
               		        sonar{1}.leg{ii}.patch{patchnum}.verts = [intsx,intsy];
				sonar{1}.leg{ii}.patch{patchnum}.overlaps = sonar{1}.leg{jj}.patch{kk}.overlaps + 1;
               		        overlaps = sonar{1}.leg{ii}.patch{patchnum}.overlaps;
               		        patchnum = patchnum + 1;
               		        plotintx = [plotintx; intsx'];
				plotinty = [plotinty; intsy'];          
               		        plotoverlaps = [plotoverlaps; overlaps];
                        end
                    end
                end
            end
	end
	
	titlestr = strcat(num2str(round((ii/size(verts,3))*100)),'% Complete');
	waitbar(ii/size(verts,3),hw,titlestr)

    end
    close(hw)
    for ii=1:length(sonar{1}.leg),
     for jj=1:length(sonar{1}.leg{ii}.patch),
    	patch(sonar{1}.leg{ii}.patch{jj}.verts(:,1),sonar{1}.leg{ii}.patch{jj}.verts(:,2),cmap(sonar{1}.leg{ii}.patch{jj}.overlaps,:));
     end
    end
    
	% now draw tracklines over the patches
	[ends] = saveVerts('returnends');
	for ii=1:size(ends,1),
    		line([ends(ii,1) ends(ii,2)],[ends(ii,3) ends(ii,4)],'Color','k','Marker','s','LineStyle',':','LineWidth',1);
	end
    	if isempty(max(plotoverlaps)),
    		plotoverlaps = 5;
    	end
	if ~get(fighandles.chart_checkbox,'Value'),
		cmap = cmap(1:max(plotoverlaps),:);
		for ic=1:max(plotoverlaps),
			labels{ic} = num2str(ic);
		end
		colormap(cmap);
		h = lcolorbar(labels,'fontweight','bold','Location','vertical','ColorAlignment','center','Tag','sonarcolorbar');
	else
		h = findobj('Tag','sonarcolorbar');
		if ~isempty(h), delete(h); end

	end
else 
	% checkbox unchecked - remove colorbar if it is there
	h = findobj('Tag','sonarcolorbar');
	if ~isempty(h), delete(h); end
end % if sonar_checkbox Value
catch, errorbox('addOverlap: Can''t get sonar checkbox value'),
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [intsx,intsy] = getIntersections(patch1x,patch1y,patch2x,patch2y,whichMap)
try,
    
    intsx = []; intsy = [];
    [intsx,intsy] = polybool('intersection',patch1x,patch1y,patch2x,patch2y);
    if length(intsx)>5,
	[intsx,intsy] = cleanpts(intsx,intsy,whichMap);
	% make sure to reclose the patch
	if length(intsx) >= 1,
		intsx(length(intsx)+1) = intsx(1);
        	intsy(length(intsy)+1) = intsy(1);
        end
    end
catch, 
	%errorbox('getIntersections: couldnt calculate intersections'),
	[intsx,intsy] = catchBadInts(patch1x,patch1y,patch2x,patch2y,whichMap);
	
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [intsx,intsy] = catchBadInts(patch1x,patch1y,patch2x,patch2y,whichMap)
try,
    
    intsx = []; intsy = [];
    err = -4;
    patch1x = roundn(patch1x,err);
    patch1y = roundn(patch1y,err);
    patch2x = roundn(patch2x,err);
    patch2y = roundn(patch2y,err);
    [intsx,intsy] = polybool('intersection',patch1x,patch1y,patch2x,patch2y);
    if length(intsx)>5,
	[intsx,intsy] = cleanpts(intsx,intsy,whichMap);
	% make sure to reclose the patch
	if length(intsx) >= 1,
		intsx(length(intsx)+1) = intsx(1);
        	intsy(length(intsy)+1) = intsy(1);
        end
    end
catch, errorbox('catchBadInts: still couldnt calculate intersections'),
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [x,y] = cleanpts(x,y,whichMap)
%CLEANPTS  Filters X and Y data to remove unnecessary points.
%   [X,Y] = CLEANPTS(X,Y) 
try,
if ~isempty([x y])
    if strcmp(whichMap,'geo'),
        err = -5;
    else
        err = 0;
    end
    for i=1:length(x),
            xrnd(i) = roundn(x(i),err);
            yrnd(i) = roundn(y(i),err);
    end
    
    indextoremove = [];
    for j=1:length(x),
            for k=1:j,
                if ~(k==j),
                if xrnd(j)==xrnd(k),
                    if yrnd(j)==yrnd(k),
                        alreadyremoved = 0;
                        for m=1:length(indextoremove),
                            if (j == indextoremove), alreadyremoved = 1; end
                        end
                        if ~alreadyremoved, indextoremove = [indextoremove,j]; end
                    end
                end
                end
            end
    end
    x(indextoremove) = [];
    y(indextoremove) = [];

if isempty(x); return; end
end
catch, errorbox('cleanpts: couldnt remove extra points'),
end


%%%%%%%%%%%%%%%%%%%%%%%%%%%
function [nover,err] = calcOverlaps(sonarrange,ts1,ts2)
% ts1 = narrow, ts2 = wide track spacing.
try,

err = 0;
dsonar = 2*sonarrange;
npw = ts1 + ts2;
if (ts2 < ts1),	err=1; nover=0;	return, end
if (ts1 >= dsonar), 
	nover=0; 
elseif (ts1 < dsonar),
	if (ts1 >= sonarrange),
		nover=2;
	else
		if (npw >= dsonar),
			nover = 2;
		elseif (npw >= (dsonar - ts1)),
			nover = 3;
		elseif (npw >= sonarrange),
			nover = 4;
		elseif (npw >= (sonarrange - (ts1/2))),
			nover = 5;
		elseif (npw >= (sonarrange - (3*ts1/2))),
			nover = 6;
		else
			nover = 0;
			err = 1;
		end
	end
end

catch, errorbox('calcOverlaps: couldnt calc num of overlaps'),
end

