function SweepLines = horizontalSweepLines(polygon,UnitWidth,Sidelap)
%This function is for internal use only. It may be removed in the future.

%horizontalSweepLines computes end points of horizontal lines that will be
%used to find intersections with the polygon and subsequently the coverage
%path.

%   Copyright 2022 The MathWorks, Inc.

%#codegen
minX=Inf;
maxX=-Inf;
minY=Inf;
maxY=-Inf;
%Find minimum  and maximum intersection points. All lines must be drawn
%from minimum to maximum X and Y to capture all possible intersections.
for i=1:1:size(polygon,1)
    if(minX>polygon(i,1))
        minX=polygon(i,1);
    end
    if(maxX<polygon(i,1))
        maxX=polygon(i,1);
    end

    if(minY>polygon(i,2))
        minY=polygon(i,2);
    end
    if(maxY<polygon(i,2))
        maxY=polygon(i,2);
    end
end

%Handle edge case where width of the polygon is less than the unit width.
if(UnitWidth>=(maxY-minY))
    sideSpacing=(maxY-minY);
    startY=minY+(maxY-minY)/2;
    numTurns=1;
    numLines=1;
    needsExtraSweep=false;
else
    sideSpacing=UnitWidth*(1-Sidelap);
    startY=minY+sideSpacing/2.0;
    Z=maxY-startY;
    [numTurns,needsExtraSweep]=uav.internal.coveragePlanner.computeTurns(Z,sideSpacing);
    numLines=numTurns+1;
end
%Start at minimum
currentY=startY;

%Pre-allocate lines.
SweepLines=zeros(numLines,4);
for index=1:1:numLines
    %Construct a line.
    %Format [xleft yleft xright yright]
    SweepLines(index,1:2)=[minX,currentY];
    SweepLines(index,3:4)=[maxX, currentY];
    currentY=currentY+sideSpacing;
end
if(needsExtraSweep)
   %Cover last row. 
   lastRowY=SweepLines(end,2);
   lastSweepY=lastRowY+(maxY-lastRowY)/2.0;
   SweepLines=[SweepLines;[minX,lastSweepY,maxX,lastSweepY]];
end



