function tpwsData = region3_calc(rho,T)
% Description:      Calculates the thermodynamic properties of water based
%                   on the IAPWS IF-97 Release for Region 3
% -------------------------------------------------------------------------
% Syntax:           tpwsData = region3_calc(rho,T)
%                   rho         Density [kg/m3]
%                   T           Temperature [K]
% -------------------------------------------------------------------------
% Output:           tpwsData    Structure containing all relevant
%                               properties

delta = rho / 322;
tau = 647.096 / T;
R = 0.461526;

[I,J,n] = region3_hfe;

phi = n(1) * log(delta);
phi_delta = n(1) / delta;
phi_delta_delta = -n(1) / delta^2;
phi_tau = 0;
phi_tau_tau = 0;
phi_delta_tau = 0;

for k = 2:40
    phi = phi + n(k) * delta^(I(k)) * tau^(J(k));
    phi_delta = phi_delta + n(k) * I(k) * delta^(I(k) - 1) * tau^(J(k));
    phi_delta_delta = phi_delta_delta + n(k) * I(k) * (I(k) - 1) * delta^(I(k) - 2) * tau^(J(k));
    phi_tau = phi_tau + n(k) * delta^(I(k)) * J(k) * tau^(J(k) - 1);
    phi_tau_tau = phi_tau_tau + n(k) * delta^(I(k)) * J(k) * (J(k) - 1) * tau^(J(k) - 2);
    phi_delta_tau = phi_delta_tau + + n(k) * I(k) * delta^(I(k) - 1) * J(k) * tau^(J(k) - 1);
end

tpwsData.T = T;
tpwsData.p = delta * phi_delta * rho * R * T / 1000;
tpwsData.v = 1/rho;
tpwsData.u = tau * phi_tau * R * T;
tpwsData.s = (tau * phi_tau - phi) * R;
tpwsData.h = (tau * phi_tau + delta * phi_delta) * R * T;
tpwsData.c_p = (-tau^2 * phi_tau_tau + (delta * phi_delta - delta * tau * phi_delta_tau)^2 / (2 * delta * phi_delta + delta^2 * phi_delta_delta)) * R;
tpwsData.c_v = -tau^2 * phi_tau_tau * R;

if (T >= 647.096) & (tpwsData.p >= 22.064)
    tpwsData.state = 'Critical';
else
    tpwsData.state = 'Liquid';
end