function []=ge_to_poly(infilename,outfilename)
%
%  []=ge_to_poly(infilename,outfilename)
%
%  This function reads path files created in Google Earth and converts them
%  into a poly.in-type ascii file which can then be used in prepfilter.m.
%  Each contiguous set of line segments created by using "path" in Google
%  Earth must be stored in a file named infilename(n).kml, where n= 1,2,
%  3... corresponds to a continuous set of line segments (i.e. and
%  individual path). Example: path1.kml, path2.kml.... The poly file is
%  stored in the current directory in a file named outfilename.
%
%  Copyright WindRiskTech, L.L.C., 2012
%  Last modified Sepember 2012
%
direction='normal'; % For closed polygon, setting to 'reverse' reverses direction 
%--------------------------------------------------------------------------
outfilename=strcat('polyfiles/',outfilename);
infilename=strcat('polyfiles/',infilename);
if exist(outfilename,'file')
    delete(outfilename)
end    
i=0;
while i >= 0
    i=i+1;
    file=strcat(infilename,num2str(i),'.kml');
    disp(file)
    try
       %[x,y,~] = read_kml(file);
       astr=kmz2struct(file);
       x=astr.Lon;
       y=astr.Lat;
    catch err %#ok<NASGU>
        msgbox([num2str(i-1) ' kml files read'])
        break
    end    
    qm=max(size(x));
    %qm2=qm/2;
    clear x1 x2 y1 y2
    %
    if abs(x(2)-x(1)) > 5 && abs(y(2)-y(1)) > 5
        x1=x(1:2:qm-1);
        x2=y(2:2:qm);
        y1=y(1:2:qm-1);
        y2=x(2:2:qm);
    else
        x1=x(1:qm-1);
        x2=x(2:qm);
        y1=y(1:qm-1);
        y2=y(2:qm);
    end   
    %
    %{
    x1=zeros(1,qm-1);
    x2=x1;
    y1=x1;
    y2=x1;
    n=0;
    for j=1:qm-1
        n=n+1;
        x1(n)=x(j);
        x2(n)=x(j+1);
        y1(n)=y(j);
        y2(n)=y(j+1);
    end
    %}
    if strcmp(direction,'reverse')
        disp('Direction reversed')
        x1f=flip(x1);
        x2f=flip(x2);
        y1f=flip(y1);
        y2f=flip(y2);
        %A=transpose([x2f';y2f';x1f';y1f']);
        A=transpose([x2f;y2f;x1f;y1f]);   % Changed October 16 2023
    else    
        %A=transpose([x1';y1';x2';y2']);
        A=transpose([x1;y1;x2;y2]);
    end     
    %dlmwrite(outfilename,A,'-append','delimiter','\t','newline','pc')
    writematrix(A,outfilename,'FileType','text','WriteMode','append','Delimiter','tab');
end    
end        