function N = N_given_TVP(x,phase)
% Calculates mole number for given temperature, volume and pressure 
% Usage :  N = N_given_TVP(x,'phase')
% Inputs:   x       = [T;V;P]
%           phase   = l (liquid) 
%                   = v (vapour)
%                   = c (above critical point)
R = 8.314;
Tc = 304.1282;
rhoc = 467.6;
MW = 44e-3;
T = x(1);
V = x(2);
P = x(3);
if phase=='l'
  a = [ 1.9245108;
       -0.62385555;
       -0.32731127;
        0.39245142];
  t = [0.34;
       1/2;
       10/6;
       11/6];
  N = V*rhoc/MW*exp(a'*(1-T/Tc).^t);
elseif phase=='v'
  a = [-1.7074879;
       -0.82274670;
       -4.6008549;
       -10.111178;
       -29.742252];
  t = [0.340;
       1/2;
       1;
       7/3;
       14/3];
  N = V*rhoc/MW*exp(a'*(1-T/Tc).^t);
elseif phase=='c'
  N = 10*P*V/(R*T);
end
  
Pt=P+1e9;
dx=0;
while abs(P-Pt)/P>1e-6
  N=N+dx;
  A=co2_sw([T;V;N]);
  Pt=-A.g(2);
  dx = -inv(A.H(2,3))*(P-Pt);
end
