function [U,x,OnN1,nsamp] = CalPipe(U,x,ind,par,scl,con,~,Ver,On1j)

% Calculation file - pipe model
%
% This function calculations the sampling domain in other variables than its
% initial definition. Furthermore, it extracts the dependent variables from
% the solution vector of the nonlinear system of equations and calculates
% dependent variables which are not included in the nonlinear system.
%
% Written by Julian Straus, Trondheim 09.12.2018
%
% The main input and output is defined as
%       U:      Structure containing the sampling domain calculated using
%               several possible approaches for independent variables 
%               definition. The output includes as well the whole input.
%
%       x:      Structure containing the state variables and new calculated
%               variables which are not calculated inside the system of
%               nonlinear equations. The output includes as well the whole
%               input.
%
% The seconday output for post analysis is given:
%       OnN1:   Vector of ones with size nsamp x 1
%
%       nsamp:  Number of sampled points.
%
%
% The necessary input is defined as
%       ind:    Vector containing the indidces of the dependent variables
%               in x.
%
%       par:    Cell structure containing the parameters used in the 
%               calculation, output of the system.
%
%       scl:    Cell structure containing the scaling factors for each unit
%               operations. The assignment is given in par.ReactSec.
%
%       con:    Physical constants, must contain
%               .R      Ideal Gas constant
%       
%       opt:    Structure containing options.
%
%       Ver:    Structure containing options.
%
%       On1j:   Vector of ones with size 1 x j (Number of chemical
%               components.

% Calculation of the number of sampling points and of the independent 
% variables which are varied for the validation space
nsamp = size(U.tot,1);
OnN1  = ones(nsamp,1);

% Calculation of the total molar flow
Q = sum(U.tot(:,3:end),2);

% Calculation of the varied independent variables
U.samp = U.tot(:,ind.in);

% Calculation of the partial pressures and mole fractions
U.Molfrac   = [Q U.tot(:,1:2) U.tot(:,4:end)./(Q*On1j(2:end))];
U.PartPress = [Q U.tot(:,2) U.tot(:,3:end).*((U.tot(:,1)./Q)*On1j)];
U.anal      = [U.tot(:,3:end)*par{1}.M U.tot(:,1) ...
               con.R*(U.tot(:,2)+273.15)./((U.tot(:,3:end)*par{1}.M)./Q)];
             
% Calculation of the component molar flowrates 
x.out = [x.tot(:,ind.out(2:3)).*(OnN1*scl{1}.Var(ind.out(2:3))) ...
         x.tot(:,ind.out(4:end)).*(x.tot(:,ind.out(1))*scl{1}.Var(ind.out(1))*On1j)];

% Combination of the outlet values
if Ver.diff
    x.red  = U.tot(:,1)-x.out(:,1);
else
    x.red  = x.out(:,1);
end