% This function computes the design and off design steady state performance
% of a bypass nozzle

function [Gas_out, Thrust] = Fan_Nozzle(Gas_in, T_amb, P_amb, Mach, D_BN)

% Declare Global Viariable Data
gam_cold = 1.4;     % Ratio of Specific Heats Estimated from (R. Sonntag et al, Fundamentals of Thermodynamics)     
cp_cold = 1005;     % Specific Heat at Constant Pressure Estimated from (R. Sonntag et al, Fundamentals of Thermodynamics)
R = 287;            % Ideal Gas Constant (J/kg/Kelvin) from (Anderson, Fundamentals of Aerodynamics)

T1 = Gas_in(1);     % Temperature In (Kelvin)
P1 = Gas_in(2);     % Pressure In (Pascal)
G1 = Gas_in(3);     % Mass Flow In (kg/s)

% Nozzle Design Parameters
A_Bypass = D_BN(1);                                          % Nozzle area (m^2)

% Bypass Nozzle equations
if P1/P_amb < 1.8939                                         % Not choked 

T2 = T1*(P_amb/P1)^((gam_cold-1)/gam_cold);                  % Exit temperature (Kelvin) (Anderson, Fundamentals of Aerodynamics)                                        
ue = sqrt(2*cp_cold*(T1-T2));                                % Exit velocity (m/s) (Anderson, Fundamentals of Aerodynamics)
G2  = P_amb/(R*T2)*ue*A_Bypass;                              % Mass flow (kg/s) (Anderson Fundamentals of Aerodynamics)
P_exit = P_amb;                                              % Exit Pressure (Pascal) (Anderson, Fundamentals of Aerodynamics)

else                                                         % Choked (sonic at minimum area location)

T2 = T1*(1+(gam_cold-1)/2)^(-1);                             % Exit Temperature (Kelvin) (Anderson, Fundamentals of Aerodynamics)
P2_throat = P1*(T2/T1)^(gam_cold/(gam_cold-1));              % Throat Pressure Clculation (Pascal) (Anderson, Fundamentals of Aerodynamics) 
ue = sqrt(gam_cold*R*T2);                                    % Exit velocity at throat (m/s) (Anderson, Fundamentals of Aerodynamics)
G2  = P2_throat/(R*T2)*ue*A_Bypass;                          % Mass flow (kg/s) (Anderson, Fundamentals of Aerodynamics) 
P_exit = P2_throat;                                          % Exit Pressure Calculation (Pascal) (Anderson, Fundamentals of Aerodynamics)

end
Gas_out = [T2 P_exit G2];                                           % Save all Gas Outputs to Vector
Thrust = G2*(sqrt(2*cp_cold*(T1-T2))-Mach*sqrt(gam_cold*R*T_amb));  % Output Thrust (Newtons) from Momentum Conservation

end
