function [sys,x0,str,ts] = s_pc(t,x,u,flag)
% t,x,u og flag sendes automatisk til denne s-funksjonen av simulink. u er
% inngangene (pådrag).
% u = pl pv wng Hng fra neste, png wl wv Htot fra forrige, 

global b
switch flag

  % INITALIZATION
  % -------------
  case 0,      
        [sys,x0,str,ts]=Initialize;
    
  % OUTPUTS 
  % -------
  case 3,
    T = u(1);
    p = u(2);
    V = u(3);
    N0 = p*V/(b.R*T);
    % Kun væske i tanken:
    N = N0;
    dN= N;
    while abs(dN)>1e-6*N
        A= ng_pr([T,V,N,N*1e-6,N*1e-6]');
        dN = (p + A.g(2))/(-A.H(2,3));
        N = N + dN;
    end
    rho = N/V*b.MW_pc(2); % [kg/m3]
    H = (-A.g(1)*T + A.g(3)*N)/N;   % [J/mol]
    
    sys = [p, rho, H]';
    
  case { 1, 2, 4, 9 }
    sys=[];
    
  % UNEXPECTED FLAGS
  % ----------------
  otherwise
    error(['Unhandled flag = ',num2str(flag)]);
    
end

% end sfuntmpl

%
%=============================================================================
% mdlInitializeSizes
% Return the sizes, initial conditions, and sample times for the S-function.
%=============================================================================
%

function [sys,x0,str,ts]=Initialize(ni)
global b 
%
% call simsizes for a sizes structure, fill it in and convert it to a
% sizes array.
%
% Note that in this example, the values are hard coded.  This is not a
% recommended practice as the characteristics of the block are typically
% defined by the S-function parameters.
%
sizes = simsizes;

sizes.NumContStates  = 0;
sizes.NumDiscStates  = 0;
sizes.NumOutputs     = 3; % p rho H
sizes.NumInputs      = 3; % T,p,V
sizes.DirFeedthrough = 1; % 0 hvis utgang ikke direkte funksjon av inngang, ellers 1
sizes.NumSampleTimes = 1; % at least one sample time is needed

sys = simsizes(sizes);


% initialize the initial conditions
x0 = []; % TVN(liq) TN(vap) TVN(ng) T(vegg)

% str is always an empty matrix
str = [];

% initialize the array of sample times
ts  = [0 0];
%data=initialize;
% end mdlInitializeSizes

