function [xx_up, yy_up, Xc1, Yc1] = create_polygon( X1, Y1, X2, Y2, is_right1,  PA, xu, yu, xl, yl, S, tol)
%% Questa funzione calcola la posizione angolare della ruota 1 (motrice) 
%  quando si genera il volume di ingranamento
%OUTPUT: 
% 1. xx_up, yy_up : coord vertici poligono chiuso lato  mandata
% 2. xx_down, yy_down : coord vertici poligono chiuso lato aspirazione

Xc1 = zeros(1,2); Yc1 = zeros(1,2); Xc2 = zeros(1,2); Yc2 = zeros(1,2);
coord1 = zeros(1,2); coord2 = zeros(1,2);

jj = 1; ii = 1;
while ii <= length(X1)
    if (Y1(ii) <= yu) && (Y1(ii) >= yl) && ( abs(X1(ii) + Y1(ii)*tand(PA)) < tol ) && (is_right1(ii) == 1)
        coord1(jj) = ii;
        Xc1(jj) = X1(ii);
        Yc1(jj) = Y1(ii);
        jj = jj + 1;
        ii = ii + round(S);
    end
    if jj == 3, break ,end
    ii = ii + 1;
end

Xc1 = Xc1(Xc1~=0);
Yc1 = Yc1(Yc1~=0);

 if length(Xc1) == 1, xx_up = 0; yy_up = 0; 
 elseif length(Xc1) == 2
     for jj = 1:2
       for ii = 1 : length(X2)
           if (Y2(ii) <= 1.1*yu) && (Y2(ii) >= 1.1*yl) && abs(X2(ii) - Xc1(jj)) <= 1e-2 * Xc1(jj) && abs(Y2(ii) - Yc1(jj)) <= 1e-2 * Yc1(jj)
               coord2(jj) = ii;
               Xc2(jj) = X2(ii);
               Yc2(jj) = Y2(ii);
               break
           else dist(ii) = sqrt( (X2(ii) - Xc1(jj))^2 + (Y2(ii) - Yc1(jj))^2 );
           end
          [M,Ind] = min(dist);
          coord2(jj) =  Ind;
       end
     end
    
    %Definizione contorno 1
    if Y1(coord1(1)) < Y1(coord1(2)), coord1 = flip(coord1); end
    if coord1(1) < coord1(2)
        c1x = X1(coord1(1) : coord1(2));
        c1y = Y1(coord1(1) : coord1(2));
    else 
        c1x = [X1(coord1(1) : end), X1(1 : coord1(2))];
        c1y = [Y1(coord1(1) : end), Y1(1 : coord1(2))];
    end
    %Definizione contorno 2
    if Y2(coord2(2)) < Y2(coord2(1)), coord2 = flip(coord2); end
    if coord2(1) < coord2(2)
        c2x = X2(coord2(1) : coord2(2));
        c2y = Y1(coord2(1) : coord2(2));
    else 
        c2x = [X2(coord2(1) : end), X2(1 : coord2(2))];
        c2y = [Y2(coord2(1) : end), Y2(1 : coord2(2))];
    end
    %Definizione poligono Area ingranamento 
    xx_up = [c1x, c2x];
    yy_up = [c1y, c2y];
   
end

end