function tpwsData = region5_calc(p,T)
% Description:      Calculates the thermodynamic properties of water based
%                   on the IAPWS IF-97 Release for Region 5
% -------------------------------------------------------------------------
% Syntax:           tpwsData = region5_calc(p,T)
%                   p           Pressure [MPa]
%                   T           Temperature [K]
% -------------------------------------------------------------------------
% Output:           tpwsData    Structure containing all relevant
%                               properties

Pi = p;
tau = 1000 / T;
R = 0.461526;

[J0,n0] = region5_gfe_ig;
[Ir,Jr,nr] = region5_gfe_r;

gamma0 = 0;
gamma0_tau = 0;
gamma0_tau_tau = 0;

for k = 1:6
    gamma0 = gamma0 + n0(k) * tau^(J0(k));
    gamma0_tau = gamma0_tau + n0(k) * J0(k) * tau^(J0(k) - 1);
    gamma0_tau_tau = gamma0_tau_tau + n0(k) * J0(k) * (J0(k) - 1) * tau^(J0(k) - 2);
end

gamma0 = log(Pi) + gamma0;
gamma0_pi = 1/Pi;
gamma0_pi_pi = -1/Pi^2;
gamma0_pi_tau = 0;

gammar = 0;
gammar_pi = 0;
gammar_pi_pi = 0;
gammar_tau = 0;
gammar_tau_tau = 0;
gammar_pi_tau = 0;

for k = 1:5
    gammar = gammar + nr(k) * Pi^(Ir(k)) * tau^(Jr(k));
    gammar_pi = gammar_pi + nr(k) * Ir(k) * Pi^(Ir(k) - 1) * tau^(Jr(k));
    gammar_pi_pi = gammar_pi_pi + nr(k) * Ir(k) * (Ir(k) - 1) * Pi^(Ir(k) - 2) * tau^(Jr(k));
    gammar_tau = gammar_tau + nr(k) * Pi^(Ir(k)) * Jr(k) * tau^(Jr(k) - 1);
    gammar_tau_tau = gammar_tau_tau + nr(k) * Pi^(Ir(k)) * Jr(k) * (Jr(k) - 1) * tau^(Jr(k) - 2);
    gammar_pi_tau = gammar_pi_tau + nr(k) * Ir(k) * Pi^(Ir(k) - 1) * Jr(k) * tau^(Jr(k) - 1);
end

tpwsData.T = T;
tpwsData.p = p;
tpwsData.v = Pi * (gamma0_pi + gammar_pi) * R * T / p;
tpwsData.u = (tau * (gamma0_tau + gammar_tau) - Pi * (gamma0_pi + gammar_pi)) * R * T;
tpwsData.s = (tau * (gamma0_tau + gammar_tau) - (gamma0 + gammar)) * R;
tpwsData.h = tau * (gamma0_tau + gammar_tau) * R * T;
tpwsData.c_p = -tau^2 * (gamma0_tau_tau + gammar_tau_tau) * R;
tpwsData.c_v = (-tau^2 * (gamma0_tau_tau + gammar_tau_tau) - (1 + Pi * gammar_pi - tau * Pi * gammar_pi_tau)^2 / (1 - Pi^2 * gammar_pi_pi)) * R;
tpwsData.state = 'Vapor';