function [Nsealed, xl, yl, xr, yr] = sealedVolumes(tup, tdown, xL, yL, xR, yR, Z)
%This function tracks last sealed tooth coordinates (left tip edge) and
%first sealed tooth coordinates (right tip edge). It also returns the
%number of contemporary sealed volumes.
%INPUT:
% tup : casing angular extension (delivery side) [deg]
% tdown : casing angular extension (suction side) [deg]
% xL, yL : vector containing tooth tip left edges coordinates
% xR, yR : vector containing tooth tip right edges coordinates
% Z : teeth number
%OUTPUT:
% Nsealed : number of comtemporry sealed volumes
% xl, yl : coordinates of the last left tooth edge in contact w/ the casing
% xr, yr : coordinates of the first right tooth edge in contact w/ the casing

tup = pi - deg2rad(tup); tdown = pi + deg2rad(tdown); %casing angular extension
                                                      %in driver gear reference frame
thL = zeros(1, length(xL)); thR = zeros(1, length(xR));
thLmin = 10000; thRmax = -10000; %initialization

%the following 'for cycle' evaluates each left tip edge angular coordinate.
%If the angular coordinate is greater than the angular coordinate of the
%delivery side casing extension then the tooth is sealed: the one closer to
%it corresponds to the last sealed tooth.
for ii = 1 : length(xL)
   % if yL(ii) > 0
        thL(ii) =  mod(atan2(yL(ii), xL(ii)), 2*pi); %angular coord. of left edges
        if thL(ii) >= tup && thL(ii) < thLmin
           thLmin = thL(ii);
           IDl = ii; %IDl contains the ID index of the last sealed tooth!!!
        end
   % end
end

%the following 'for cycle' evaluates each right tip edge angular coordinate.
%If the angular coordinate is lesser than the angular coordinate of the
%suction side casing extension then the tooth is sealed: the one closer to
%it corresponds to the first sealed tooth.
for ii = 1 : length(xR)
    if yR(ii) < 0
        thR(ii) = mod(atan2(yR(ii), xR(ii)), 2*pi);
        if thR(ii) <= tdown && thR(ii) > thRmax
           thRmax = thR(ii);
           IDr = ii; %IDr contains the ID index of the first sealed tooth!!!
        end
    end
end

%Calculate number of contemporary sealed volumes given IDl, IDr
%identification index: 
 if IDr < IDl, Nsealed = IDl - IDr;
 else, Nsealed = Z - (Idr - IDl);
 end

 xl=xL(IDl); yl=yL(IDl);   %coordinates of the last sealed tooth (delivery side)
 xr=xR(IDr); yr=yR(IDr);   %coordinates of the first sealed tooth (suction side)

 end

