function [r,ndot,mdot] = Rrate_NewDist_Ver4(T,wH2,wN2,in,kval,d)

% This function calculates the reation rate of ammonia in kg NH3/kg cat,s.
%
% The difference to the function "Rrate_NewDist.m" is given by the
% change of independent variables to the mass fraction of hydrogen and
% nitrogen.
%
% The required input is given by
%   T       Temperature of the stage
%   wH2     Mass fraction of hydrogen of the stage
%   wN2     Mass fraction of nitrogen of the stage
%   in      Array containing the inlet conditions for the pressure
%   kval    Structure containing parameters for the reaction rate constant
%   d       Catalyst activity

% Import of CASADI
import casadi.*

% Calculation of the mass fractions of the streams
if isa(T,'casadi.MX')
    m = MX.zeros(3,numel(wH2));
else
    m = zeros(3,numel(wH2));
end
m(1,:) = wH2';
m(2,:) = wN2'; 
m(3,:) = 1-wH2'-wN2'; 

% Calculation of the mass and molar flow of the streams
mdot = m*in(1);
ndot = mdot./([2 28 17]'*ones(1,numel(wH2)));

% Calculation of the molar fractions
n = ndot./(ones(3,1)*sum(ndot));

% Calculation of the reaction rate constants
k1  = kval.Afor*exp(-kval.Eafor./(kval.R*(T(:)'+273))); 	% Forward reaction rate constant
k2  = kval.Abac*exp(-kval.Eabac./(kval.R*(T(:)'+273)));     % Backward reaction rate constant

% Calculation of the partial pressure [bar]
pH2  = n(1,:)*in(2);
pN2  = n(2,:)*in(2); 
pNH3 = n(3,:)*in(2) ;

% Calculation of the reaction rate and transformation of it
r = [1 1 1]'*(k1.*pN2.*pH2.^1.5./pNH3 - k2.*pNH3./pH2.^1.5);% [kmol N2/ m3 cat, h]
r = ([3*2 28 -2*17]'*ones(1,numel(wH2))).*r/2200/3600;     % [kg [H2 N2 NH3]/ kg cat, s]
r = (1+d)*4.75*r;                                           % Multiply by 4.75 to match industrial instability