function [sys,x0,str,ts]=OLGAConnection(t,x,u,flag,s)

% 'u' is the inputvector to OLGA defined by 'SIM.InputVariables.Definition'
% (including control)

switch flag,
  case 0         
    [sys,x0,str,ts] = mdlInitializeSizes(t,x,u,s); % Initialization
  case 2
    sys = mdlUpdate(t,x,u,s);
  case 3
    sys = mdlOutputs(t,x);  % Calculate outputs
  case {1,4}
    sys = []; % do nothing
    case 9
        sys=StopOLGA(s.ConNo);
otherwise
    error(['unhandled flag = ',num2str(flag)]);
end

%=============================================================================
% mdlInitializeSizes
% Return the sizes, initial conditions, and sample times for the S-function.
%=============================================================================
%
function [sys,x0,str,ts] = mdlInitializeSizes(t,x,u,s)

n_meas_loc=findstr(s.TrendVariables,'$');
n_meas=0;
for i=1:length(n_meas_loc)-1
    n_meas=n_meas+length(findstr(strtrim(s.TrendVariables(n_meas_loc(i):n_meas_loc(i+1)-1)),' '));
end
if isempty(i)
    i=0;
end
n_meas=n_meas+length(findstr(strtrim(s.TrendVariables(n_meas_loc(i+1):end)),' '));
sizes = simsizes;
sizes.NumContStates  = 0;
sizes.NumDiscStates  = n_meas;
sizes.NumOutputs     = n_meas;
sizes.NumInputs      = sum(s.InputVariables.Dimensions);
sizes.DirFeedthrough = 0;
sizes.NumSampleTimes = 1;

sys = simsizes(sizes);
str = [];
x0  = zeros(1,n_meas);

%Start OLGA server
pause(2);
[ds, dw] = dos(s.OlgaCommand); 
pause(2);
if ~isfield(s,'ConNo')
    s.ConNo=[];
end
%Connect to server
[err, errmsg] = OsiConnect([s.OlgaConnect],s.ConNo);

%Check connection
[err, errmsg] = OsiPing(s.ConNo);

%Load the inputfile and initialize OLGA
[err, errmsg] = OsiStart(s.InputFile,s.ConNo);

if isempty(s.RestartFile) == 0
   [err, errmsg] = OsiLoadSnap(s.RestartFile,s.ConNo);
end

%Subscribe for pipeline trend variables
[err, errmsg] = OsiSetTrendVar(s.TrendVariables,s.ConNo);

%Advertise input variable
[err, errmsg] = OsiSetInputVar([s.InputVariables.Definition],[s.InputVariables.Dimensions],s.ConNo);

pause(2);

% Call Olga to get initial conditions
[t, x0, err] = OsiSendTrendData(s.TrendVariables,s.ConNo);
%x0  = zeros(1,dim_trendvar+dim_profilevar);
ts  = [s.SampleTime 0];   % sample time: [period, offset]

function sys=mdlUpdate(t,x,u,s)
%Calls OLGA to simulate:
Ts=s.SampleTime;
current_time=OsiGetTime(s.ConNo);
inputvector = u';

[currentOLGA_time, trendoutputs, positions , profileoutputs, err, errmsg] = OsiSim(current_time+Ts,inputvector,s.ConNo);

sys = [trendoutputs,profileoutputs];

function sys = mdlOutputs(t,x,u)
    sys = x;
    
function sys=StopOLGA(ConNo);

%Stop the server
[err, errmsg] = OsiStopServer(ConNo);

%Close connection to server
[err, errmsg] = OsiDisconnect(ConNo);

sys=[];