% detection intersection between polygons
function [intsctFlag CombineShapeMatrix] = DetectIntersectionPolygons(Matrix1,Matrix2)
    Poly1 = Convert2PlotFormat(Matrix1);
    Poly2 = Convert2PlotFormat(Matrix2);
    C1 = mean(Poly1);
    C2 = mean(Poly2);
    theta = atan(imag(C1-C2)/real(C1-C2));
    R_mtheta = [cos(theta) sin(theta); -sin(theta) cos(theta)];
    PR1 = R_mtheta*[real(Poly1); imag(Poly1)];
    PolyR1 = PR1(1,:)+j*PR1(2,:);
    PR2 = R_mtheta*[real(Poly2); imag(Poly2)];
	PolyR2 = PR2(1,:)+j*PR2(2,:);
    C1R = mean(PolyR1); C2R = mean(PolyR2);    
    
    if real(C1R)<real(C2R)
        PL = PolyR1;
        PR = PolyR2;
    else
        PL = PolyR2;
        PR = PolyR1;
    end

    [LminVal LminIdx]=min(imag(PL));
    [LmaxVal LmaxIdx]=max(imag(PL));
    PLrightPoint = [];
    idx = LminIdx; flag = 1;
    while flag
       if idx==LmaxIdx
           flag = 0;
       else
       end        
       PLrightPoint = [PLrightPoint PL(idx)];
       idx = max([mod(idx+1,length(PL)) 1]);
    end

    [RmaxVal RmaxIdx] = max(imag(PR));
    [RminVal RminIdx] = min(imag(PR));
    PRleftPoint = [];
    idx = RmaxIdx; flag = 1;
    while flag
        if idx ==RminIdx
            flag=0;
        else
        end
        PRleftPoint = [PRleftPoint PR(idx)];
        idx = max([mod(idx+1,length(PR)) 1]);
    end
    
    IntersectionPoint=[];
    for idx = 1:length(PLrightPoint)-1
        Line = [PLrightPoint(idx) PLrightPoint(idx+1)];
        for Ridx = 1:length(PRleftPoint)-1
            TestLine = [PRleftPoint(Ridx) PRleftPoint(Ridx+1)];
            [xloc yloc] = polyxpoly(real(Line),imag(Line),real(TestLine),imag(TestLine)); 
            if ~isempty([xloc yloc])
                IntersectionPoint = [IntersectionPoint xloc+j*yloc];
            else
            end
        end
    end
    if isempty(IntersectionPoint)
        intsctFlag=0;
        CombineShapeBack=[];
        CombineShapeMatrix=[];
        PLIDX=[];
        PRIDX=[];
    else
        intsctFlag=1;
        [CombineShape PLIDX PRIDX] = BuildNewShape(PL,PR,IntersectionPoint);
            %%%%%%%%%%%%%% Rotate Back %%%%%%%%%%%%%%%%%
        RBack = [cos(theta) -sin(theta); sin(theta) cos(theta)];
        CSBack = RBack*[real(CombineShape); imag(CombineShape)];
        CombineShapeBack = CSBack(1,:)+j*CSBack(2,:); 
        CombineShapeMatrix = [real(CombineShapeBack); imag(CombineShapeBack)];
        CombineShapeMatrix = CombineShapeMatrix(:,1:length(CombineShapeBack)-1);
    end
    

end